本章介紹了如何驗證姓名,電子郵件和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"]);
}
}
?>
運行示例» 下一步是展示如何防止從形式,當用戶提交表單清空所有輸入字段。