close[x]


PHP

PHP-Home PHP-Environment Setup PHP-Syntax PHP-Run PHP in XAMPP PHP-Variable PHP-Comment PHP-Datatype PHP-String PHP-Operators PHP-Decision PHP-loop PHP-Get/Post PHP-Do While loop PHP-While loop PHP-For loop PHP-Foreach loop PHP-Array PHP-Multidimensional Arrays PHP-Associative Arrays PHP-Indexed Arrays PHP-Function PHP-Cookies. PHP-Session PHP-File upload PHP-Email PHP-Data & Time PHP-Include & Require PHP-Error PHP-File I/O PHP-Read File PHP-Write File PHP-Append & Delete File PHP-Filter PHP-Form Validation PHP-MySQl PHP-XML PHP-AJAX



learncodehere.com





PHP - Form Validation

An HTML form contains various input fields such as text box, checkbox, radio buttons, submit button, and checklist, etc. .

the user has entered information in all the required fields should validates that the information provided by the user is valid and correct.

You need to validate this things:

  • Empty String : If the user leaves the required field empty, it will show an error message

  • Example : Empty String

    
     if (emptyempty ($_POST["name"])) 
     {  
     $errMsg = "Error! You didn't enter the Name.";  
     echo $errMsg;  
     }
    else
    {  
     $name = $_POST["name"];  
     }    

  • Validate String : If the name field does not receive valid input from the user, then it will show an error message:

  • Example : Validate String

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

  • Validate Numbers : If the Mobile no field does not receive numeric data from the user, the code will display an error message

  • Example : Validate Numbers

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

  • Validate Email : If the field does not contain a valid email address, then the code will display an error message:

  • Example : Validate Email

    
     $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) )
     {  
     $ErrMsg = "Email is not valid.";  
     echo $ErrMsg;  
     }
      else 
    {  
     echo "Your valid email address is: " .$email;  
     }    

  • Validate URL : If the field does not contain a valid URL, the code will display an error message

  • Example : Validate URL

    
     $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;  
     }    

  • Input length : The input length validation restricts the user to provide the value between the specified range

  • Example : Input length

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


    Create and validate a Registration form

    Create a registration form using HTML and perform server-side validation.


    Example : Form Validation

    File Name : formvalidation.php

    
    <!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 (emptyempty($_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 (emptyempty($_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 (emptyempty($_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 (emptyempty($_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 (emptyempty ($_POST["gender"])) {  
                $genderErr = "Gender is required";  
        } else {  
                $gender = input_data($_POST["gender"]);  
        }  
      
        //Checkbox Validation  
        if (!isset($_POST['agree'])){  
                $agreeErr = "Accept terms of services before submit.";  
        } else {  
                $agree = input_data($_POST["agree"]);  
        }  
    }  
    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> Agree to Terms of Service:
            <input type="checkbox" name="agree">
            <span class="error">* <?php echo $agreeErr; ?> </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>
                    


    Result :

    Run File : localhost/formvalidation.php

    When the above code runs on a browser, the output will be like the screenshot below.

    php form validation