Today, I will discuss regarding form validation in core PHP. when the user submitted the form at that time required for input field validation. there are two types of validation, first is server side and second is client side. see below example of server-side validation.

Required field, email validation and number required .. etc I will give validation information by our post.

See below code, that is an array wise creating a form validation, whenever error generate at that time count error array element, if count greater than 0, we are showing the error message.

<?php
if(isset($_POST['btnadd']))
{
    $first_name  = $_POST['txtFname'];
    $last_name   = $_POST['txtLname'];
    $address     = $_POST['txtAddress'];
    $email       = $_POST['txtEmail'];
    $mobile      = $_POST['txtMobile'];
	
	$error=array();
	
	if(empty($first_name)){
	   $error['first_name']="First Name is required";
	}
	if(empty($last_name)){
	   $error['last_name']= "Last Name is required";
	}
	if(empty($email)){
	   $error['email']= "Email is required";
	}
	else
	{
	   if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
		 $error['email']= "Invalid email format"; 
	   }
	}
	if (empty($mobile)) {
	   $error['mobile']= "Mobile is required";
	}
	else{
	   if (preg_match('/[^0-9]+$/', $mobile)){
		 $error['mobile']= "Only Number allowed"; 
	   }
	}
	$count=count($error);
	if($count>0){
		echo "Validation is Success";
	}
}
?>
<style>
     .error {color: #FF0000;}
</style>
<form method="post" name="frmAdd">
        <table align="center">
            <tr>
                <td colspan="2" align="center">Add Record</td>
            </tr>

            <tr>
                <td>First Name</td>
                <td>
		 <input type="text" name="txtFname" value="<?php echo @$first_name; ?>"> 
		 <span class = "error">* <?php echo '<br>'.@$error['first_name'];?></span>
		</td>
            </tr>
            <tr>
                <td>Last Name</td>
                <td>
		 <input type="text" name="txtLname" value="<?php echo @$last_name; ?>"> 
		 <span class = "error">* <?php echo '<br>'.@$error['last_name'];?></span>
               </td>
            </tr>
            <tr>
                <td>Address</td>
                <td><textarea name="txtAddress" rows="4" cols="16"></textarea> </td>
            </tr>
            <tr>
                <td>Email</td>
                <td>
		 <input type="text" name="txtEmail" value="<?php echo @$email; ?>"> 
		 <span class = "error">* <?php echo '<br>'.@$error['email'];?></span>
		</td>
            </tr>
            <tr>
                <td>Mobile</td>
                <td>
		  <input type="text" name="txtMobile" value="<?php echo @$mobile; ?>"> 
		  <span class = "error">* <?php echo '<br>'.@$error['mobile'];?></span>	
		</td>
            </tr>
            <tr>
                <td colspan="2" align="center">
                  <input type="submit" value="Add" name="btnadd"> 
               </td>
            </tr>
        </table>
</form>
Connect With Facebook