Validating Form
×
Home Courses Community Support
Validating Form

Some time user make typing mistake while entering details. And some users make it just for fun. As we are working on web form, so we need to get as much as possible correct information. To do so, we apply some validation on our web form. For example, we make sure that the name, email, phone entered by user are in correct format or the fields are not blank.

See below code to check validation-

<!docty html>
<html>
<head>
	<style>
	.space{
	margin-left:50px;
	margin-bottom:20px;
	}
	.msq{
	margin-left:35px;
	}	
	.btn{
	margin-left:95px;
	margin-top:35px;
	}
	.error{
	color:#FF0000;
	}
	</style>
</head>
<body>

<?php
// define variables and set to empty values
$userNameErr = $userPhoneErr = $userEmailErr = $userMsgErr = "";
$userName = $userPhone = $userEmail = $userMsg = "";
$validate=false;

if ($_SERVER["REQUEST_METHOD"] == "POST") {
	$userName=trim($_POST["userName"]);
	$userPhone=trim($_POST["userPhone"]);
	$userEmail=trim($_POST["userEmail"]);
	$userMsg=trim($_POST["userMsg"]);
	if (empty($userName)) {
		$userNameErr = " Name is required";
	}else if(!preg_match("/^[a-zA-Z ]*$/",$userName)) {	 
		$userNameErr = " Only letters and white space allowed";
	}else if (empty($userPhone)) {
		$userPhoneErr = " Phone number is required";
	}else if(preg_match("/^[a-zA-Z ]*$/",$userPhone)) {
		$userPhoneErr = " Only numeric value is allowed";
	}else if(!filter_var($userEmail, FILTER_VALIDATE_EMAIL)) {
		$userEmailErr = " Enter valid email address";
	}
	else if (empty($userMsg)) {
		$userMsgErr = " Message field can not be blank.";
	}
	else{
		$userName = test_input($userName);
		$userPhone = test_input($userPhone); 		 
		$userEmail = test_input($userEmail); 		 
		$userMsg = test_input($userMsg);
		$validate=true;
	}
}   
function test_input($data) {
   $data = stripslashes($data);
   $data = htmlspecialchars($data);
   return $data;
}


?>
<h2>Contact Us</h2>
<form method="post">
<label>Name</label> <input  class="space" name="userName" type="text" ><span class="error"><?php echo $userNameErr;?></span> <br>
<label>Phone</label> <input  class="space" name="userPhone" type="text" ><span class="error"><?php echo $userPhoneErr;?></span> <br>
<label>Email</label> <input  class="space" name="userEmail" type="text" ><span class="error"><?php echo $userEmailErr;?></span> <br>
<label>Message</label> <textarea  class="msq" rows="5" cols="40" name="userMsg"> </textarea><span class="error"><?php echo $userMsgErr;?></span> <br>
<input class="btn" type="submit" name="submit">
</form>

<?php if($validate){?>
<h2>Thanks for writing to us. We will contact you shortly.</h2>
<h3>Your contact details and message are as below:</h3>
<b>Name:</b> <?php echo "&nbsp;"."$userName"."<br>"; ?>
<b>Phone:</b> <?php echo "&nbsp;"."$userPhone"."<br>"; ?>
<b>Email:</b> <?php echo "&nbsp;"."$userEmail"."<br>"; ?>
<b>Message:</b> <?php echo "&nbsp;"."$userMsg"."<br>"; ?>
<?php }?>
</body>
</html>


In the above code we use the web form created in previous heading. To submit this form we have used the Post method as it is more secure. And to validate the enteries, we use following-

$_Server: It is an array containing information such as headers, paths, and script locations. The entries in this array are created by the web server. It is a superglobal variable.

REQUEST_METHOD: If the REQUEST_METHOD is post then it will perform the validation if applied or will display the blank form.

Trim: It remove unnessary spaces from both side of string.

Preg_match: It is an function which match the string with given pattern and return true only if the pattern match.

Filter_var: This function is used to filter the value. It return filtered data and return false if filter fail.

Stripslashes: This function un-quote the quoted string and remove backslashes. (If string have double backslashes, it will return with single backslash.)

Htmlspecialchars: This function converts special characters to HTML entities.

Explanation, Initially we define the error variables and the variables to get input from user via form. We set all the values to NULL and use a variable and set its value to false. When you will run the above code on server, $_SERVER["REQUEST_METHOD"] will check if it need to display contact form only or need to perform validation. It will perform validation only if you submit the form. To perform validation, all the mentioned validation function will be run in if else statement. When all the conditions are true, we pass the variable values (getting from user) in to function test_input() and assign that value to origional variable name. And at last pass true in variable $validate.

Now to display the form result we use $validate variable. We print all the values if $variable is true. If any condition will false then no value will be printed because $variable is set to true when all conditions are true.

Note: In this form we did not use <form action=""> because we are showing the values on same page. Action is necessary when we pass the values from one page to another.


Form will show error one by one like below image


 

← Preview

Designing Enquiry Form

Next →

Integrate Mail Function within Form

NOTES

Our mission is to provide highly effective and quality education via innovative solutions. Geeksdemy look forward to bridge the gap between in-demand technology and academics in order to deliver innovative, easy, interesting and affordable learning across the Globe.

Courses

  • Python
  • Game Development with Unity 3D
  • Arduino
  • PCB & Circuit Designing
  • Robotics and Embedded C
  • 8051/8052 Embedded Systems
  • QuadCopter & UAV
  • MATLAB with Robotics
  • Raspberry Pi
Learn On the Go!
Get the Android App
Get the iOS App