Server Side Form Validations Using PHP

In this short tutorial, I will show you how to validate a form using server-side code (PHP) rather than using a Library like Jquery.
You can download the code snippet and a working model at the end.

Overview

In order to do this, we will need following files

  • Index.php

Index.php

The Index file contains the code that is used to display the simple HTML user interface as well as the PHP code that will validate the form.
First, we will capture all the submitted data from the form using the Method POST into separate variables and then use them to validate them using PHP built-in validation mechanisms.

<?php

$errorMessage = "";
$username = "";
$email = "";
$contact = "";

// Check if Form is Submitted
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
// Fill Variables with Data
$username = $_POST['name_txt'];
$email = trim($_POST['email_txt']);
$contact = trim($_POST['contact_txt']);

//Start Validating Fields
if(!ctype_alnum($username)){
$errorMessage = "Username is not Alpha-Numeric";
}

elseif(strlen($username) < 3 OR strlen($username) > 10){
$errorMessage = "Username Should be between 3-10 Characters";
}

elseif(!filter_var($email,FILTER_VALIDATE_EMAIL)){
$errorMessage = "Enter a Valid Email Address";
}

elseif (!ctype_digit($contact) OR strlen($contact) != 10) {
$errorMessage = "Enter a Valid Contact number";
}

else{
$errorMessage = "Successful Request ";
}

}
else{
$errorMessage = "Welcome to Server Validation";
}

?>

<html xmlns="http://www.w3.org/1999/html">
<head>
<title>Tutorial-04</title>
</head>

<body>
<center>

<div id="main_form">

<form method="post">
<h3>Contact Form</h3>
<p id="returnmessage"><?php echo $errorMessage ?></p>
<label>Name: <span>*</span></label> &nbsp; &nbsp; &nbsp; &nbsp;
<input type="text" name="name_txt" placeholder="Name"/> </br>
<label>Email: <span>*</span></label> &nbsp; &nbsp; &nbsp; &nbsp;
<input type="text" name="email_txt" placeholder="Email"/> </br>
<label>Contact No:<span>*</span></label>
<input type="text" name="contact_txt" placeholder="10 digit Mobile no."/> </br>
<input type="submit" value="Submit"/>
</form>

</div>

</center>

</body>
</html>

When the form is filled and the user clicks on the Submit button, a request of type POST will be sent to the server. As soon as the server receives the request it will check the $_POST variable if it contains the needed form details.
After capturing those details, captured data will be sent through a hierarchy of validations which will give out a resulting message if anything fails or if the validation passes. Then that message will is printed back in the form.

Download The codes here.

Download the complete source code.

Grab the the free working demo Intantly!

You have Successfully Suscribed!

Leave a Reply

Your email address will not be published. Required fields are marked *