PHP Form Validation

PHP Form Validation


In HTML form contains a number of inputs: text fields, a radio button, a multiple-option select list, a checkbox, and a submit button. These inputs will be validated to ensure that the user has supplied a value for each one.

The validation rules for the form above are as follows:  

Field Validation Rules
Valid string Required. + Must only contain letters and whitespace
Valid E-mail Required. + Must contain a valid email address (with @ and .)
Valid URL Optional. If present, it must contain a valid URL
 Input Length restricts the user to provide the value between the specified range
Valid Number alidates that the field will only contain a numeric value.

Valid String : The code contain only alphabets and whitespace, for example - name. If the name field does not receive valid input from the user, then it will show an error message:

Example : 

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

Valid E-mail : A valid email must contain @ and . symbols. PHP provides various methods to validate the email address. 

Example:

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

 Valid URL :In HTML FORM ,If the field does not contain a valid URL, the code will display an error message, i.e., "URL is not valid".

Example :

$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, for Example - Mobile Number. A valid mobile number must have 10 digits.

Example:

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

 

Valid Number :The below code validates that the field will only contain a numeric value. For example - Mobile no. If the Mobile no field does not receive numeric data from the user, the code will display an error message:

Example :

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