In our previous tutorial we created a CRUD application successfully. In this tutorial, we will learn how to apply validation in the same.

There are two ways to validate a form, “Server Side Validation” and “Client Side Validation”. The difference between two is that, The Server Side Validation is performed on the server using server side scripting language like PHP, JSP, ASP, ASP.net etc. while the Client Side Validation is performed on user’s system using client side scripting language like JavaScript, jQuery, Prototype etc. It is recommended to do both type of validation, to provide more security for our Web Application/Website.

In this tutorial we will learn how to do client side validation. We will using JavaScript for it. We can do the validation using different logic of code. Below are three way of JavaScript validation:

  • In this, each error will get alert message.
  • This method will have one alert box, where all the errors are displayed.
  • By displaying all error messages in HTML form element.

 

This is the HTML form we are going to use, which is the same form we used in our CRUD application. We have two fields in the form, country name and country code.

<form action="form_back.php" method="post" onsubmit="return validation()">
	<div class="row">
		<div class="cols">Country Code</div>
		<div class="cols"><input type="text" id="ccode" name="ccode" value="<?php if(isset($row['country_code'])){echo $row['country_code'];}?>"></div>
	</div>
	<div class="row">
		<div class="cols">Country Name</div>
		<div class="cols"><input type="text" id="cname" name="cname" value="<?php if(isset($row['country_name'])){echo $row['country_name'];}?>"></div>
	</div>
	<div class="row">
		<div class="cols"><input type="submit" name="submit" value="submit"></div>
		<div class="cols"><input type="hidden" name="cid" value="<?php if(isset($_GET['cid'])){echo $_GET['cid'];} ?>"</div>
	</div>
</form>

We will use onsubmit event on form and call JavaScript function name “validation”. When user clicks on the submit button of form element, the validate function “validation()” will automatically be called. In JavaScript we can fetch form element value using getElementById (‘id’ attribute of form element) or getElementByName (‘name’ attribute of form element). Here, we will fetch form element value using ‘id’, so we have to give ‘id’ attribute to each input that we want to validate, which are ‘ccode’  for country code and ‘cname’ for country name.

 We are going to check for,

1) The Form should not be empty (All are require fields),

2) Characters must be alphanumeric

3) Specific character’s length should be as per defined.

To use this code, simply copy and paste the content in script tag (<script></script>) after the HTML.

 

Method 1: JavaScript validation by using alert each for error message, one by one

function validation(){
  var errorStatus = true;
  if(document.getElementById('ccode').value !="")
  {
    var letterNumber = /^[0-9a-zA-Z]+$/;
    if(document.getElementById('ccode').value.match(letterNumber)) 
    {
      if(document.getElementById('ccode').value.length>3)
      {
        alert("country code must be in 3 latters or less than");
        document.getElementById('ccode').focus();
        return false;
      }

    }
    else
    {
      alert("please enter only letters and numbers in country code");
      document.getElementById('ccode').focus();
      return false;
    }
    
  }else
  {
    alert("please enter country code");
    document.getElementById('ccode').focus();
    return false;
  }
  if(document.getElementById('cname').value !="")
  {
    var letterNumber = /^[0-9a-zA-Z\s]+$/;
    if(document.getElementById('cname').value.match(letterNumber)) 
    {
      if(document.getElementById('cname').value.length>40)
      {
        alert("country name must be in 40 latters or less than");
        document.getElementById('ccode').focus();
        return false;
      }

    }else{
      alert("please enter only letters and numbers in country name");
      document.getElementById('cname').focus();
      return false;
    }
    
  }else{
    alert("please enter country name");
    document.getElementById('cname').focus();
    return false;
  }
}

So, how does this validation works exactly?

We can get the value of form element with, “document.getelementbyid(‘id’).value”. For required field, we have to check user submitted input is empty or not. If it is empty, we will simply display error message in alert function and return false to stop the form submission. If value is not empty, complier goes to next line of code and checks for other validation.

In our case, we have check for alphanumeric, in which we will be using “Regular Expression” and match function. We will check it with user submitted value. If not matched, it will display error message and stop the execution using return false. If it matches with regular expression, we then check other validation like length of input value is less than 40 or not. If is not less than 40 then it’ll return false and stop the execution. We have to follow same process for all the form elements, which we consider for validation.

Note:-we use a document.getelementbyid(‘ ‘).focus() to focus on the input box which ‘id’ returns false.

 

Method 2: JavaScript’s client side validation by using one alert box to display all error messages

function validation(){

var errorStatus = true;

var errormsg="";

if(document.getElementById('ccode').value !="")

{

var letterNumber = /^[0-9a-zA-Z]+$/;

if(document.getElementById('ccode').value.match(letterNumber)) {

if(document.getElementById('ccode').value.length>3){

errormsg += "country code must be in 3 latters or less than\n";

}

}else{

errormsg += "please enter only letters and numbers in country code\n";

}

}else{

errormsg += "please enter country code\n";

}

if(document.getElementById('cname').value !="")

{

var letterNumber = /^[0-9a-zA-Z]+$/;

if(document.getElementById('cname').value.match(letterNumber)) {

if(document.getElementById('cname').value.length>40){

errormsg += "country code must be in 40 latters or less than\n";

}

}else{

errormsg += "please enter only letters and numbers in country name\n";

}



}else{

errormsg += "please enter country name\n";

}

if(errormsg!=""){

alert(errormsg);

return false;

}else{

return true;

}

}

In this method we display all error message in one alert box. The conditions are same as the previous method. We want to display all messages at once, we need one variable to store error message. For that we will use variable ‘errormsg’ to store all error messages on it.

We also use one other variable ‘errorStaus’ to store status of th error like TRUE or FALSE. After checking all validations, just like previous method, at the end we will concat all error message strings in ‘errormsg’ variable and return it at the end of the function with the return false, so execution will stop. If there is no other error message, it returns true and form will submit successfully.

 

Method 3: JavaScript validation by displaying all error messages in HTML form element

function validation(){

var errorStatus = true;

var errormsg="";

if(document.getElementById('ccode').value !="")

{

var letterNumber = /^[0-9a-zA-Z]+$/;

if(document.getElementById('ccode').value.match(letterNumber)) {

if(document.getElementById('ccode').value.length>3){

errormsg += "country code must be in 3 latters or less than"+"<br>";

}

}else{

errormsg += "please enter only letters and numbers in country code"+"<br>";

}

}else{

errormsg += "please enter country code"+"<br>";

}

if(document.getElementById('cname').value !="")

{

var letterNumber = /^[0-9a-zA-Z]+$/;

if(document.getElementById('cname').value.match(letterNumber)) {

if(document.getElementById('cname').value.length>40){

errormsg += "country name must be in 40 latters or less than";

}

}else{

errormsg += "please enter only letters and numbers in country name";

}

}else{

errormsg += "please enter country name";

}

if(errormsg!=""){

document.getElementById('errormsg').innerHTML=errormsg;

return false;

}else{

return true;

}

}

In this method we will display all errors on top of the form. We created a div with id at the top of the form. The process of the validation is same as the previous method in which we displayed all the message in alert box at once. Here we can use same variable which has all error messages, but instead of display into alert, we will put it in form element div using innerHTML.

Note: The innerHTML property sets the HTML syntax for the element.

We hope this validation article and our CRUD application tutorial helped you understand how to develop a small PHP application with JavaScript validation. In the next tutorial, we will give more detailed example of JavaScript validation with different type of form elements.

Have any question or query? Want to add more information for this article? Just comment below to share whats on your mind after reading this.
If you like our article, please share it with your friends who will find this helpful.