How To Validate Email and URL In PHP Forms
Throughout this article, we will be discussing how to validate email addresses, URLs, and other fields on PHP forms, so that we will be able to fill them out correctly.
The validation of user input is an essential part of developing a reliable and secure web application. Email addresses and URLs are commonly inserted into web forms and applications, as well as in other types of apps. When processing these inputs, it is important that they are formatted correctly and are valid before they are processed.
This tutorial will show you how to validate data on the server-side and on the client-side, as well as how to avoid some common pitfalls when working with these types of inputs.
Validate Name
Below is a simple example of checking if the name field contains only letters, dashes, apostrophes, and whitespace and age contains only numbers..
There will be an error message stored if the value of the name field is not valid:
$firstname = input_validation($_POST["firstname"]); if (!preg_match("/^[a-zA-Z-‘ ]*$/",$firstname)) { $fnameErr = "Only letters and white space allowed"; } age = input_validation($_POST["age"]); if (!preg_match("/^[0-9 ]*$/", $age)) { $ageErr = "Only numbers allowed"; }
When preg_match() is called, a string is searched for a pattern, and if the pattern exists, it returns true, otherwise it returns false.
Validate Email
Using PHP’s filter_var() function is the easiest and most reliable way of checking whether an email address is well-formed or not.
If the email address provided is not a well-formed one, then the following error message will be displayed in the code:
$email = input_validation($_POST["email"]); if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $emailErr = "Invalid email format"; }
Validate URL
Below is a code example on how to verify whether the URL address syntax is valid (this regular expression also allows dashes in the URL address).
If there is a syntax error in the URL address, then store an error message that states:
$linkedin = input_validation($_POST["linkedin"]); if (!preg_match("/^(?:(?:https?|ftp):\\/\\/|www.)[-a-z0-9+&@#\\/%?=~_|!:,.;]*[-a-z0-9+&@#\\/%=~_|]/i", $linkedin)) { $linkedInErr = "URL is not valid"; }
Php Form Validate Email and Url
This is what the script looks like now: