PHP 进行表单验证
一个HTML表单中包含各种输入字段,比如文本框、复选框、单选按钮、提交按钮和复选框等等。这些输入字段需要进行验证,以确保用户已经在所有必填字段中输入了信息,并验证用户提供的信息是否有效和正确。
不能保证用户提供的信息总是正确的。PHP会在服务器端验证由HTML表单提交的数据。您需要验证一些事项:
- 空字符串
- 验证字符串
- 验证数字
- 验证电子邮件
- 验证URL
- 输入长度
空字符串
下面的代码检查字段是否为空。如果用户将必填字段留空,它将显示错误信息。将这些代码放在验证所需字段的位置。
if (empty (_POST["name"])) {errMsg = "Error! You didn't enter the Name.";
echo errMsg;
} else {name = $_POST["name"];
}
验证字符串
下面的代码检查该字段只包含字母和空格,例如-姓名。如果姓名字段未从用户获得有效输入,则会显示错误消息:
$name = $_POST ["Name"];
if (!preg_match ("/^[a-zA-z]*$/", $name) ) {
$ErrMsg = "Only alphabets and whitespace are allowed.";
echo $ErrMsg;
} else {
echo $name;
}
验证数字
下面的代码验证字段只会包含数值。 例如 – 手机号码。如果手机号码字段未接收到用户的数字数据,则代码将显示错误消息:
$mobileno = $_POST ["Mobile_no"];
if (!preg_match ("/^[0-9]*$/", $mobileno) ){
$ErrMsg = "Only numeric value is allowed.";
echo $ErrMsg;
} else {
echo $mobileno;
}
验证电子邮件
有效的电子邮件地址必须包含@和.符号。PHP提供了多种方法来验证电子邮件地址。在这里,我们将使用正则表达式来验证电子邮件地址。
下面的代码通过HTML表单验证用户提供的电子邮件地址。如果字段不包含有效的电子邮件地址,则代码将显示错误消息:
$email = $_POST ["Email"];
$pattern = "^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$^";
if (!preg_match ($pattern, $email) ){
$ErrMsg = "Email is not valid.";
echo $ErrMsg;
} else {
echo "Your valid email address is: " .$email;
}
输入长度验证
输入长度验证限制用户提供指定范围内的值,例如 – 手机号码。有效的手机号码必须有10位数字。
给定的代码将帮助您应用长度验证于用户输入:
$mobileno = strlen ($_POST ["Mobile"]);
$length = strlen ($mobileno);
if ( $length < 10 && $length > 10) {
$ErrMsg = "Mobile must have 10 digits.";
echo $ErrMsg;
} else {
echo "Your Mobile number is: " .$mobileno;
}
验证URL
以下代码验证用户通过HTML表单提供的网站的URL。如果字段不包含有效的URL,代码将显示错误消息,即”URL不有效”。
$websiteURL = $_POST["website"];
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {
$websiteErr = "URL is not valid";
echo $websiteErr;
} else {
echo "Website URL is: " .$websiteURL;
}
按钮点击验证
以下代码验证用户是否点击了提交按钮,并将表单数据以以下方法之一(get或post)发送到服务器。
if (isset (_POST['submit']) {
echo "Submit button is clicked.";
if (_SERVER["REQUEST_METHOD"] == "POST") {
echo "Data is sent using POST method ";
}
} else {
echo "Data is not submitted";
}
现在我们将把所有这些验证应用到一个HTML表单中,以验证字段。通过这样,您可以详细了解这些代码如何用于验证表单。
使用HTML创建一个注册表单,并执行服务器端验证。按照以下指示操作:
创建并验证一个注册表单
<!DOCTYPE html>
<html>
<head>
<style>
.error {color: #FF0001;}
</style>
</head>
<body>
<?php
// define variables to empty values
nameErr =emailErr = mobilenoErr =genderErr = websiteErr =agreeErr = "";
name =email = mobileno =gender = website =agree = "";
//Input fields validation
if (_SERVER["REQUEST_METHOD"] == "POST") {
//String Validation
if (empty(_POST["name"])) {
nameErr = "Name is required";
} else {name = input_data(_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*/",name)) {nameErr = "Only alphabets and white space are allowed";
}
}
//Email Validation
if (empty(_POST["email"])) {emailErr = "Email is required";
} else {
email = input_data(_POST["email"]);
// check that the e-mail address is well-formed
if (!filter_var(email, FILTER_VALIDATE_EMAIL)) {emailErr = "Invalid email format";
}
}
//Number Validation
if (empty(_POST["mobileno"])) {mobilenoErr = "Mobile no is required";
} else {
mobileno = input_data(_POST["mobileno"]);
// check if mobile no is well-formed
if (!preg_match ("/^[0-9]*/",mobileno) ) {
mobilenoErr = "Only numeric value is allowed.";
}
//check mobile no length should not be less and greator than 10
if (strlen (mobileno) != 10) {
mobilenoErr = "Mobile no must contain 10 digits.";
}
}
//URL Validation if (empty(_POST["website"])) {
website = "";
} else {website = input_data(_POST["website"]);
// check if URL address 语法 is valid
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",website)) {
websiteErr = "Invalid URL";
} }
//Empty Field Validation
if (empty (_POST["gender"])) {
genderErr = "Gender is required";
} else {gender = input_data(_POST["gender"]);
}
//Checkbox Validation
if (!isset(_POST['agree'])){
agreeErr = "Accept terms of services before submit.";
} else {agree = input_data(_POST["agree"]);
}
}
function input_data(data) {
data = trim(data);
data = stripslashes(data);
data = htmlspecialchars(data);
return data;
}
?>
<h2>Registration Form</h2>
<span class = "error">* required field </span>
<br><br>
<form method="post" action="<?php echo htmlspecialchars(_SERVER["PHP_SELF"]); ?>" >
Name:
<input type="text" name="name">
<span class="error">* <?php echo nameErr; ?> </span>
<br><br>
E-mail: <input type="text" name="email">
<span class="error">* <?php echoemailErr; ?> </span>
<br><br>
Mobile No:
<input type="text" name="mobileno">
<span class="error">* <?php echo mobilenoErr; ?> </span>
<br><br>
Website: <input type="text" name="website">
<span class="error"><?php echowebsiteErr; ?> </span>
<br><br>
Gender:
<input type="radio" name="gender" value="male"> Male
<input type="radio" name="gender" value="female"> Female
<input type="radio" name="gender" value="other"> Other
<span class="error">* <?php echo genderErr; ?> </span>
<br><br>
Agree to Terms of Service:
<input type="checkbox" name="agree">
<span class="error">* <?php echoagreeErr; ?> </span>
<br><br>
<input type="submit" name="submit" value="Submit">
<br><br>
</form>
<?php
if(isset(_POST['submit'])) {
if(nameErr == "" && emailErr == "" &&mobilenoErr == "" && genderErr == "" &&websiteErr == "" && agreeErr == "") {
echo "<h3 color = #FF0001> <b>You have sucessfully registered.</b> </h3>";
echo "<h2>Your Input:</h2>";
echo "Name: " .name;
echo "<br>";
echo "Email: " .email;
echo "<br>";
echo "Mobile No: " .mobileno;
echo "<br>";
echo "Website: " .website;
echo "<br>";
echo "Gender: " .gender;
} else {
echo "<h3> <b>You didn't filled up the form correctly.</b> </h3>";
}
}
?>
</body>
</html>
抱歉,我无法直接在这个文本编辑器中保留HTML格式。但是,我可以用文本形式为您翻译英文内容。请提供您需要翻译的英文句子或段落。
当上面的代码在浏览器上运行时,输出结果如下图所示:
记住 ,我们没有使用数据库来存储注册用户的数据。