PHP Form Validation

PHP Basics No Comments

PHP Form Validation

PHP Form Validation

– There are 2 ways to validate forms. The first is using Javascript, which is also known as client-side validations and the second one is using PHP, which is also known as server-side validations. In this tutorial, we’ll cover server-side validations by using PHP functions.

Common PHP Form Validations

1. Empty String: The following code snippet will check that the input field is not left blank while submitting the form. If the user leaves any required field empty, in this example Name,  this code will generate an error message. This is the most common PHP form validation.

if (empty ($_POST["name"])){
$errorMessage = "Name field can not be left blank. Please enter your name.";
echo $errorMessage;
} else{
$name = $_POST["name"];
}

2. Validate String: The following code snippet checks if the input field contains only alphabets and whitespace. So, if the Name input field does not get the valid input from the user, then the below code will generate an error message as shown below:

$name = $_POST ["name"];

if (!preg_match ("/^[a-zA-z]*$/", $name) ){
$errorMessage = "Only Alphabets and Whitespaces are allowed in Name field.";
echo $errorMessage;
} else{
echo $name;
}

3. Validate Number: The following code snippet validates that the field will only contain a numeric value. If the mobile number doesn’t receive numeric data from the user, as input then the following code will generate an error message as shown below:

$mobilenumber = $_POST ["mobile_number"];

if (!preg_match ("/^[0-9]*$/", $mobilenumber) ){
$errorMessage = "Only numeric value is allowed in Mobile number field.";
echo $errorMessage;
} else{
echo $mobilenumber;
}

4. Validate Email: The valid email must contain @ &. symbols. PHP provides various methods to validate email input fields. We can use regular expressions to validate the email address as shown below:

$email = $_POST ["email_address"];
$email_valid_pattern = "^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$^";

if (!preg_match ($email_valid_pattern, $email) ){
$errorMessage = "Entered email address is invalid.";
echo $errorMessage;
} else{
echo "Your valid email address is: " .$email;
}

We can even use the inbuilt feature of PHP to validate emails: FILTER_VALIDATE_EMAIL as below:

$email = $_POST ["email_address"];
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errorMessage = "Entered email address is invalid.";
echo $errorMessage;
} else{
echo "Your valid email address is: " .$email;
}

Both of these methods are popularly used in PHP form validation, you can use any of these.

5. Input Field Length Validation:
The following code snippet validates that the mobile field will have exactly 10 digits. If the entered mobile number value comprises less or more than 10 digits then the following code will generate an error message as shown below:

$mobilenumber = strlen ($_POST ["mobile_number"]);
$length = strlen ($mobilenumber);

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

6. Validate URL: The following code snippet validates that the website URL is valid. If the URL is not valid, it will generate an error message as shown below:

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

7. Button Click Validate: The following code snippet validates that the user clicks on the submit button and sends the form data to the server using one of the following methods – GET or POST.

if (isset ($_POST['submit']) {
echo "Submit button is clicked.";
if ($_SERVER["REQUEST_METHOD"] == "POST"){
echo "Data is sent using POST method ";
}
} else {
echo "Data is not submitted via form.";
}

Below is the complete code with a form and all the above mentioned

PHP form validations:

<!DOCTYPE html>	
<html>	
<head>	
<style>	
.error {color: #FF0001;}	
</style>	
</head>	
<body>
<?php	
// define variables to empty values	
$nameError = $emailError = $mobile_numberError = $genderError = $websiteError = $hobbyError = "";	
$name = $email = $mobile_number = $gender = $website = $hobby = "";	

//Input fields validation	

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

    //Email Validation	 	if (empty($_POST["email"])) {		   $emailError = "Email is required";		} else {
       $email = input_data($_POST["email_address"]);	
         	 // check that the e-mail address is well-formed	
         	 if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { 
            $emailError = "Invalid email format";		    }
    }	
    //Number Validation		
    if (empty($_POST["mobile_number"])) {
       	$mobile_numberError = "Mobile no is required";		
       } else {
        $mobile_number = input_data($_POST["mobile_number"]);		   
        // check if mobile no is well-formed		    
        if (!preg_match ("/^[0-9]*$/", $mobile_number) ) { 
            $mobile_numberError = "Only numeric value is allowed.";		    
        }
        //check mobile no length should not be less and greater than 10	
         		if (strlen ($mobile_number) != 10) {	
         		    $mobile_numberError = "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)){

         	$websiteError = "Invalid URL";

        }
        }

    //Empty Field Validation	
    if (empty ($_POST["gender"])){

        $genderError = "Gender is required";	
    }else{

        $gender = input_data($_POST["gender"]);	
    }

    //Checkbox Validation	
    if (!isset($_POST['hobbies'])){	
        $hobbyError = "You must select hobby.";	
    }else{

        $hobby = input_data($_POST["hobbies"]);
    }	

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 $nameError; ?> </span>
    <br><br>	
    E-mail:

    <input type="text" name="email_address">	
    <span class="error">* <?php echo $emailError; ?> </span>
    <br><br>	
    Mobile No:	
    <input type="text" name="mobile_number">	
    <span class="error">* <?php echo $mobile_numberError; ?> </span>
    <br><br>	
    Website:	
    <input type="text" name="website">	
    <span class="error"><?php echo $websiteError; ?> </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 $genderError; ?> </span>
    <br><br>	
    Hobbies:
    <input type="checkbox" name="hobbies" value="Reading"> Reading
    <input type="checkbox" name="hobbies" value="Writing"> Writing
    <input type="checkbox" name="hobbies" value="Playing"> Playing
    <span class="error">* <?php echo $hobbyError; ?> </span>
    <br><br>

    <input type="submit" name="submit" value="Submit">

    <br><br>	 	 	 	 	 	 	 	 	 	 	 	 	 	 
</form>	
<?php	
    if(isset($_POST['submit']))	{

        if($nameError == "" && $emailError == "" && $mobile_numberError == "" && $genderError == "" && $websiteError == "" && $hobbyError == ""){

            echo "<h3 color = #FF0001> <b>You have sucessfully submitted the form.</b> </h3>";	
            echo "<h2>Your Input Fields are as below:</h2>";	
            echo "Name: " .$name;	
            echo "<br>";	
            echo "Email: " .$email;	
            echo "<br>";	
            echo "Mobile No: " .$mobile_number;	
            echo "<br>";	
            echo "Website: " .$website;	
            echo "<br>";	
            echo "Gender: " .$gender;	
            echo "<br>";
            echo "Hobby: " .$hobby;
        } else {	
            echo "<h3> <b>Carefully check the form fields before submitting it.</b> </h3>";	
        }

    }	
?>	
</body>	
</html>

I hope you’ve understood the concept of PHP Form Validation today. Now you can click the below link to check the demo.
The Download link to download the files used in this tutorial is also available on this page.
PHP Form Validation Demo

For professional website and application development, contact us here.

4.5 2 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments