本章介绍了如何验证姓名,电子邮件和URL。
PHP - 验证名称
下面的代码显示了一个简单的方法来检查,如果名称字段只包含字母和空格。 如果名称字段的值是无效的,那么存储的错误信息:
$name = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z ]*$/",$name))
{
$nameErr = "Only letters and white space allowed";
}
该的preg_match()函数查找字符串的模式,返回true如果模式存在,否则为false。 |
PHP - 验证电子邮件
检查是否电子邮件地址以及形成的最简单,最安全的方法是使用PHP的filter_var()函数。
在下面的代码,如果不能很好地形成的电子邮件地址,然后将其存储的错误消息:
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr =
"Invalid email format";
}
PHP - 验证URL
下面的代码显示了一种方法来检查,如果URL地址语法是否有效(this regular expression also allows dashes in the URL) 。 如果URL地址语法无效,那么存储的错误信息:
$website = test_input($_POST["website"]) ;
if
(! preg_match("/\b(?:(?:https?|ftp) :\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website))
{
$websiteErr = "Invalid URL";
}
PHP - 验证姓名,E-mail和网址
现在,脚本如下:
例
<?php
// define variables and set to empty values
$nameErr = $emailErr
= $genderErr = $websiteErr = "";
$name = $email = $gender = $comment =
$website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is
required";
} else {
$name = test_input($_POST["name"]);
// check if name
only contains letters and whitespace
if
(!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["email"]))
{
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
//
check if e-mail address is well-formed
if (!filter_var($email,
FILTER_VALIDATE_EMAIL)) {
$emailErr =
"Invalid email format";
}
}
if (empty($_POST["website"]))
{
$website = "";
} else {
$website = test_input($_POST["website"]);
// check if
URL address syntax is valid (this regular expression also allows dashes in
the URL)
if
(!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website))
{
$websiteErr = "Invalid URL";
}
}
if (empty($_POST["comment"]))
{
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}
if (empty($_POST["gender"]))
{
$genderErr = "Gender is required";
} else
{
$gender = test_input($_POST["gender"]);
}
}
?>
运行示例» 下一步是展示如何防止从形式,当用户提交表单清空所有输入字段。