Validate Form Data with PHP

Clean Form Data

The first thing is to pass all variables through PHP's htmlspecialchars() function. The htmlspecialchars() function converts special characters to HTML entities. If a user tries to enter some code in the form, it will not be executed and is now safe to be displayed on a page or inside an e-mail.

Next, strip unnecessary characters (extra space, tab, newline) from the user input data with the PHP trim() function.

Finally, remove backslashes (\) from the user input data with the PHP stripslashes() function.

To avoid writing the same code over and over again, create a function that will do all the checking.

function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;

Required Fields

Required fields cannot be empty and must be filled out in the HTML form. An error message is displayed if needed. You can use PHP empty() function. If the $_POST variable is empty, an error message is displayed, and if it is not empty, it sends the user input data through the test_input() function.

Validate Name

Name field contains letters and whitespace only. If the value of the name field is not valid, then error message is displayed.

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

The preg_match() function searches a string for pattern, returning true if the pattern exists, and false otherwise.

Validate E-Mail

The best way to check whether an email address is well-formed is to use PHP's filter_var() function.

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

The filter_var() Function checks if the variable is a valid email address.

Star ActiveStar ActiveStar ActiveStar ActiveStar Active