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.


In order to do this, we will need following files

  • 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.


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

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

//Start Validating Fields
$errorMessage = "Username is not Alpha-Numeric";

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

$errorMessage = "Enter a Valid Email Address";

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

$errorMessage = "Successful Request ";

$errorMessage = "Welcome to Server Validation";


<html xmlns="">


<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"/>




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.

[rad_rapidology_inline optin_id=optin_13]