Forms Validate E-mail and URL

Form fields need to be validated through the special php functions to avoid any security issues. Below code will help you to validate the email and URLs before entering the database.

Validate Name

This code will show you how to validate the name fields in the form.

$name = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}

Code explanation

In the above code are using if statement to validate the field input. The preg_match() function specially developed to check the string for the pattern. It returns true if the pattern exists and false otherwise.

The if statement is using the preg_mmatch() function which has following string in it ("/^[a-zA-Z ]*$/"). If any of the special characters exist in the function then it will return the error message "Only letters and white space allowed".

Validate E-mail

The best way to validate an email address is checking it with the php filter_var() function. It checks the valid email address and returns the value true or false.

Example

$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}

Code explanation

In the above code, we are using filter_var() function to check the valid email address. If it is not valid then it will show the error message “Invalid email format”.

Validate URL

You can use preg_match() function to validate URLs. You can add additional syntax to verify the valid email address.

Example:

$website = test_input($_POST["website"]);
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {
$websiteErr = "Invalid URL";
}

Code Explanation

In the above code, we have declared the additional characters to validate URLs. If none of the characters from above matches in the URL then it will show the error message “Invalid URL” to the user.

Related Posts

Leave a Reply