验证邮箱和URL
1. 验证名字
以下代码展示的简单方法检查 name 字段是否包含字母和空格。如果 name 字段无效,则存储一条错误消息:
$firstName = validate_input($_POST["firstName"]);
if (!preg_match("/^[a-zA-Z ]*$/",$firstName)) {
$nameError = "只允许字母和空格!";
}
preg_match()函数检索字符串的模式,如果模式存在则返回true,否则返回false。
2. 验证 E-mail
以下代码展示的简单方法检查 e-mail 地址语法是否有效。如果无效则存储一条错误消息:
$userEmail = validate_input($_POST["userEmail"]);
if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$userEmail)) {
$emailError = "无效的 email 格式!";
}
3. 验证 URL
以下代码展示的方法检查 URL 地址语法是否有效(这条正则表达式同时允许 URL 中的斜杠)。如果 URL 地址语法无效,则存储一条错误消息:
$websiteUrl = validate_input($_POST["websiteUrl"]);
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=?~_|]/i",$websiteUrl)) {
$urlError = "无效的 URL";
}
4. 验证 Name、E-mail、以及 URL
现在,脚本是这样的:
<?php
// 初始化变量为空值
$errorName = $errorEmail = $errorGender = $errorUrl = "";
$inputName = $inputEmail = $inputGender = $inputComment = $inputWebsite = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["inputName"])) {
$errorName = "名字是必填项";
} else {
$inputName = sanitize_input($_POST["inputName"]);
// 检查名字是否包含字母和空格
if (!preg_match("/^[a-zA-Z ]*$/",$inputName)) {
$errorName = "名字只能包含字母和空格";
}
}
if (empty($_POST["inputEmail"])) {
$errorEmail = "电子邮件是必填项";
} else {
$inputEmail = sanitize_input($_POST["inputEmail"]);
// 检查电邮地址语法是否有效
if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$inputEmail)) {
$errorEmail = "无效的电子邮件格式";
}
}
if (empty($_POST["inputWebsite"])) {
$inputWebsite = "";
} else {
$inputWebsite = sanitize_input($_POST["inputWebsite"]);
// 检查 URL 地址语法是否有效
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=?~_|]/i",$inputWebsite)) {
$errorUrl = "无效的 URL";
}
}
if (empty($_POST["inputComment"])) {
$inputComment = "";
} else {
$inputComment = sanitize_input($_POST["inputComment"]);
}
if (empty($_POST["inputGender"])) {
$errorGender = "性别是必填项";
} else {
$inputGender = sanitize_input($_POST["inputGender"]);
}
}
function sanitize_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>