PHP Web page Validation

PHP Web page Validation


A web page having multiple forms


Users may mistakenly submit the data through the form with empty fields or in the wrong format.

PHP script must ensure that required fields are complete and submitted data is in valid format.

PHP provides some inbuilt function using these functions that input data can be validated.

empty() function will ensure that text field is not blank it is with some data, function accepts variable as an argument and returns TRUE when the text field is submitted with empty string, zero, NULL or FALSE value.

Is_numeric() function will ensure that data entered in a text field is a numeric value, the function accepts a variable as an argument and returns TRUE when the text field is submitted with numeric value.

preg_match() function is specifically used to performed validation for entering text in the text field, function accepts a "regular expression"

argument and a variable as an argument which has to be in a specific pattern. Typically it is for validating email, IP address and pin code in a form.

For example a PHP page formvalidation.php is having three text fields name, mobile number and email from user, on clicking Submit button a data will be submitted to PHP script validdata.php on the server, which will perform three different validation on these three text fields, it will check that name should not be blank, mobile number should be in numeric form and the email is validated with an email pattern.


<!DOCTYPE html>
<html>
<head>
 <title>cwipedia.in</title>
</head>
<body>
<form method="post" action="Val.php">
 
 Name:<input type="text" name="name"><br>
 Mob No:<input type="text" name="mno"><br>
 Email Id:<input type="text" name="email"><br>
 <input type="submit" name="sub" value="Submit">
</form>
</body>
</html>
Output:


<?php
if(empty($_POST['name']))
{
echo "Name cannot be blank";
}
if(!is_numeric($_POST['mno']))
{
 echo "<br>Mobile Number should be in nums";
}
if(!preg_match("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$^",$_POST['email']))
{
 echo "<br>Enter valid email id";
}
?>
Output:


Comments