PHP Form Validation - Validate E-mail and URL
- Previous Page PHP Form Required
- Next Page PHP Form Validation
This section shows how to validate name, email, and URL.
PHP - Validate Name
The following code demonstrates a simple method to check if the name field contains letters and spaces. If the name field is invalid, store an error message:
$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 the string and returns true if the pattern exists, otherwise returns false.
PHP - Validate E-mail
The following code demonstrates a simple method to check if the email address syntax is valid. If it is invalid, store an error message:
$email = test_input($_POST["email"]); if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email)) { $emailErr = "Invalid email format!"; }
PHP - Validate URL
The following code demonstrates a method to check if the URL syntax is valid (this regular expression also allows slashes in the URL). If the URL syntax is invalid, store an error message:
$website = test_input($_POST["website"]); if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%", =~_|]/i,$website)) { $websiteErr = "Invalid URL"; }
PHP - Validate Name, E-mail, and URL
Now, the script looks like this:
Example
<?php // Define variables and set them 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"; } $name = test_input($_POST["name"]); // Check if the name contains letters and spaces if (!preg_match("/^[a-zA-Z ]*$/",$name)) { $nameErr = "Only letters and white space allowed"; } } if (empty($_POST["email"])) { $emailErr = "Email is required"; } $email = test_input($_POST["email"]); // Check if the email address syntax is valid if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email)) { $emailErr = "Invalid email format"; } } if (empty($_POST["website"])) { $website = ""; } $website = test_input($_POST["website"]); // Check if the URL address language is valid (this regular expression also allows underscores in URLs) if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%", =~_|]/i,$website)) { $websiteErr = "Invalid URL"; } } if (empty($_POST["comment"])) { $comment = ""; } $comment = test_input($_POST["comment"]); } if (empty($_POST["gender"])) { $genderErr = "Gender is required"; } $gender = test_input($_POST["gender"]); } } ?>
Next, I will explain how to prevent the form from clearing all input fields after the user submits the form.
- Previous Page PHP Form Required
- Next Page PHP Form Validation