Home  >  Article  >  Backend Development  >  PHP Form Validation - Validate Email and URL

PHP Form Validation - Validate Email and URL

巴扎黑
巴扎黑Original
2016-11-12 09:22:111680browse


PHP Form Verification - Verify Email and URL

PHP Form Required

PHP Form Completion

This section shows how to verify name, email and URL.

PHP - Validate Name

The following code shows a simple way to check if the name field contains letters and spaces. If the name field is invalid, an error message is stored:

$name = test_input($_POST["name"]);

if (!preg_match("/^[a-zA-Z ]*$/",$ name)) {

$nameErr = "Only letters and spaces allowed!";

}

Note: The preg_match() function retrieves the pattern of a string and returns true if the pattern exists, otherwise it returns false.

PHP - Verify E-mail

The following code shows a simple way to check whether the e-mail address syntax is valid. Store an error message if invalid:

$email = test_input($_POST["email"]);

if (!preg_match("/([w-]+@[w-]+.[w-] +)/",$email)) {

$emailErr = "Invalid email format! ";

}

PHP - Verify URL

The method shown in the following code checks whether the URL address syntax is valid (this regular expression formula also allows slashes in URLs). If the URL address syntax is invalid, an error message is stored:

$website = test_input($_POST["website"]);

if (!preg_match("/b(?:(?:https?|ftp): //|www.)[-a-z0-9+&@#/%?=~_|!:,.;]*[-a-z0-9+&@#/%

=~_| ]/i",$website)) {

$websiteErr = "Invalid URL";

}

PHP - Verify Name, Email, and URL

Now, the script looks like this:

Example


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn