PHP Form Validation

An HTML form consists of different kinds of input fields such as text box, radio button, checkbox, submit button, etc. In our previous tutorial, we have seen how to capture data using text box and display on the screen. In this tutorial, you will learn how to validate input field data before processing data.

We will implant a few security features to validate the user input data so that user can not insert potentially harmful data that compromise the website security or might break the application.

Below are some of the most commonly used validation on PHP input field.

  1. Empty String
  2. Validate String
  3. Validate Numbers
  4. Input length
  5. Validate Email
  6. Validate URL

#1. Empty String Validation

The below lines of code checks if the field is submitted without giving any input. If the field is mandatory, it will show an error.

if (empty ($_POST["name"])) {
$errorMsg = "Error! Name cannot be empty";
echo $errorMsg;
} else {
$name = $_POST["name"];
}

#2. Validate String in PHP

If you want to validate string, for example, you want to accept only alphabets and white space, you can use the below codes.

$firstname = $_POST ["firstname"];
if (!preg_match ("/^[a-zA-z]*$/", $name) ) {
$ErrorMsg = "Only alphabets and whitespace are allowed.";
echo $ErrorMsg;
} else {
echo $firstname;
}

#3. Validate Number in PHP

The below code check if only number value is provided in the specific field. In this case we are validating mobile number. If user provide non-numeric value in this field, it will show error.

$mobileno = $_POST ["mobile_no"]; 
if (!preg_match ("/^[0-9]*$/", $mobileno) ){ 
$ErrorMsg = "Only numeric value is allowed."; 
echo $ErrorMsg; 
} else { 
echo $mobileno; 
}

#4. Input Length Validation in PHP

The input length validation restricts a user to provide the values for a specific range – for example mobile no. A valid mobile number must have 10 digits.

In order to validate the length of the input field, you can use the below code.

$mobileno = strlen ($_POST ["mobile"]); 
$length = strlen ($mobileno); 

if ( $length < 10 && $length > 10) { 
$ErrorMsg = "Mobile must have 10 digits."; 
echo $ErrorMsg; 
} else { 
echo "Your Mobile number is: " .$mobileno; 
}

#4. Validate Email in PHP

Validation of email addresses is one of the basic form validation in PHP. A valid email address must contain @ and . symbol in it. In this example, we will use regular expression to validate an email address.

The below code will validate an email address provided by the end-user through HTML form. If the user does not provide valid email address, it will show an error.

$email = $_POST ["email"]; 
$pattern = "^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$^"; 
if (!preg_match ($pattern, $email) ){ 
$ErrorMsg = "Your email is not valid."; 
echo $ErrorMsg; 
} else { 
echo "Your email address is: " .$email; 
}

#6. Validate URL in PHP

The below code validates the URL of any website provided by the user via HTML form. If the field does not contain a valid URL, it will display an error message, i.e., “URL is not valid”.

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

Now let create one complete HTML form to accept user’s input and validate the same.

<!DOCTYPE html> 
<html> 
<head> 
<style> 
.error {color: #FF0001;} 
</style> 
</head> 
<body> 

<?php 
// define variables to empty values 
$nameErr = $emailErr = $mobilenoErr = $genderErr = $websiteErr = $agreeErr = ""; 
$name = $email = $mobileno = $gender = $website = $agree = ""; 

//Input fields validation 
if ($_SERVER["REQUEST_METHOD"] == "POST") { 

//String Validation 
if (empty($_POST["name"])) { 
$nameErr = "Name is required"; 
} else { 
$name = input_data($_POST["name"]); 
// check if name only contains letters and whitespace 
if (!preg_match("/^[a-zA-Z ]*$/",$name)) { 
$nameErr = "Only alphabets and white space are allowed"; 
} 
} 

//Email Validation 
if (empty($_POST["email"])) { 
$emailErr = "Email is required"; 
} else { 
$email = input_data($_POST["email"]); 
// check that the e-mail address is well-formed 
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { 
$emailErr = "Invalid email format"; 
} 
} 

//Number Validation 
if (empty($_POST["mobileno"])) { 
$mobilenoErr = "Mobile no is required"; 
} else { 
$mobileno = input_data($_POST["mobileno"]); 
// check if mobile no is well-formed 
if (!preg_match ("/^[0-9]*$/", $mobileno) ) { 
$mobilenoErr = "Only numeric value is allowed."; 
} 
//check mobile no length should not be less and greator than 10 
if (strlen ($mobileno) != 10) { 
$mobilenoErr = "Mobile no must contain 10 digits."; 
} 
} 

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

//Empty Field Validation 
if (empty ($_POST["gender"])) { 
$genderErr = "Gender is required"; 
} else { 
$gender = input_data($_POST["gender"]); 
} 
} 
function input_data($data) { 
$data = trim($data); 
$data = stripslashes($data); 
$data = htmlspecialchars($data); 
return $data; 
} 
?> 

<h2>Registration Form</h2> 
<span class = "error">* required field </span> 
<br><br> 
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" > 
Name: 
<input type="text" name="name"> 
<span class="error">* <?php echo $nameErr; ?> </span> 
<br><br> 
E-mail: 
<input type="text" name="email"> 
<span class="error">* <?php echo $emailErr; ?> </span> 
<br><br> 
Mobile No: 
<input type="text" name="mobileno"> 
<span class="error">* <?php echo $mobilenoErr; ?> </span> 
<br><br> 
Website: 
<input type="text" name="website"> 
<span class="error"><?php echo $websiteErr; ?> </span> 
<br><br> 
Gender: 
<input type="radio" name="gender" value="male"> Male 
<input type="radio" name="gender" value="female"> Female 
<input type="radio" name="gender" value="other"> Other 
<span class="error">* <?php echo $genderErr; ?> </span> 
<br><br> 
<input type="submit" name="submit" value="Submit"> 
<br><br> 
</form> 

<?php 
if(isset($_POST['submit'])) { 
if($nameErr == "" && $emailErr == "" && $mobilenoErr == "" && $genderErr == "" && $websiteErr == "" && $agreeErr == "") { 
echo "<h3 color = #FF0001> <b>You have sucessfully registered.</b> </h3>"; 
echo "<h2>Your Input:</h2>"; 
echo "Name: " .$name; 
echo "<br>"; 
echo "Email: " .$email; 
echo "<br>"; 
echo "Mobile No: " .$mobileno; 
echo "<br>"; 
echo "Website: " .$website; 
echo "<br>"; 
echo "Gender: " .$gender; 
} else { 
echo "<h3> <b>You didn't filled up the form correctly.</b> </h3>"; 
} 
} 
?> 

</body> 
</html>

Below will be the output once you run the code in the browser.

PHP form validation example

Once you fillup the form and click on the submit button, it will display the below message.

PHP form validation result

 

 

Please get connected & share!

Advertisement