JavaScript Form Validation (Invoice Form)

This tutorial comes on second number on my series of making online invoice sample with pdf invoice and email delivery system.
In this tutorial I am going to use JavaScript form validation to forms field to get valid input from user. This is very important that form should only process valid data. As we know that in most case we use database to hold the input comes from the HTML form. If forms, in case of spammer user, sends the garbage data which have no meaning to our requirement and this data will occupy additional space in our database. It also increase our labour, and we have to check manually data of databases and delete unnecessary data. So it is better practice to check data validity as much as on user end i.e. on receiving input data from where user is making entry on the form. As we know that JavaScript is user end language and therefore we are making JavaScript form validation. We already learn how to make a simple form which tends to auto adjust in the given width. If you want to start at beginning of this tutorial series then you can first check my previous tutorial about simple form making at given link below:-
Make Online Invoice Sample with pdf Invoice and email delivery system form

What we are doing and validating in our tutorial.
1. javascript email validation
2. Javascript date validation and input format
3. Recieve only numbers input for numeric amounts
4. Blank Fileds should not be received.
5. Auto sum total field
6. Show JQuery Calendar when focus on Date Field

javascript form validation

Implementing JavaScript Form Validation

Rename “invoice_form_sample.php” with name “invoice_form_validated.php” and create a Javascript_validate.js file in the same folder where your input form resides. We shall write all our JavaScript form validation functions in this file. This javascript file should be included in the input form “invoice_form_validated.php” under the head tag. To include script file we shall write following code on the form under head tag:-

 

<script src="javascript_validate.js"></script>

Javascript Email Validation

Email which has a fixed pattern i.e. emaple@gmail.com. Beginning with a string name and @ of symbol and some domain name like gmail.com. Write following function to javascript_validate.js file:

 

function validate()
{
 
    var x = document.myform.return_email.value;
    var atpos = x.indexOf("@");
    var dotpos = x.lastIndexOf(".");
    if (atpos< 1 || dotpos<atpos+2 || dotpos+2>=x.length) {
        alert("Not a valid e-mail in return email field");
		 document.myform.return_email.focus() ;
        return false;
    }
    return( true );
}

The above function is checking the input from the email textbox exists in the form and returning false if the input email is not like the correct pattern otherwise it returns true value. We have two input fields for emails i.e. one for invoice sender and other for receiver. So we have another validation check in the validation function.

 

function validate()
{
 
    var x = document.myform.return_email.value;
    var atpos = x.indexOf("@");
    var dotpos = x.lastIndexOf(".");
    if (atpos< 1 || dotpos<atpos+2 || dotpos+2>=x.length) {
        alert("Not a valid e-mail in return email field");
		 document.myform.return_email.focus() ;
        return false;
    }

var x = document.myform.to_email.value;
    var atpos = x.indexOf("@");
    var dotpos = x.lastIndexOf(".");
    if (atpos< 1 || dotpos<atpos+2 || dotpos+2>=x.length) {
        alert("Not a valid e-mail address in forwarding email field");
		 document.myform.to_email.focus() ;
        return false;
}
       return( true );
 }

This function is called in input form under the form tag on “onsubmit” event. So we have to add the following lines on the invoice form “invoice_form_validated.php”. The code will look like this.

 

<form class="form" method="post" name="myform" action="" enctype="multipart/form-data" onsubmit="return(validate());">

When user press submit button to send form. This javascript validator function will check is the email pattern is true, then it’s ok the form will be submitted. If not the form will stop and not to be submitted and ready for correction to be make as message box is triggered telling where exactly the error is occurring and also it will set the focus cursor to that text field.

Javascript Blank Fields Validation

While submitting the form, a main function of javascript validation is to check whether an important field is not sending a blank values. For the purpose we have to check that following should not be sent blank.

1. Name of Company
2. First description field
3. First price/amount value field
So we add following code to our validate function.

 

// check whether company name is blank
 
   if( document.myform.to_name.value == "" )
   {
     alert( "Name/Company Field is Blank" );
     document.myform.to_name.focus() ;
     return false;
   }

//check whether at least first description is not blank

 if( document.myform.descrip1.value == "" )
   {
     alert( "Atleast 1 Description is required" );
     document.myform.descrip1.focus() ;
     return false;
   }
   
   //check whether at least one price field is not blank 
   
   
    if( document.myform.prow1.value == "" )
   {
     alert( "Atleast one price should be set" );
     document.myform.prow1.focus() ;
     return false;
   }

Validate 03 Input Date Fields

Now it is turn to validate 03 input date fields. For the purpose we use three JavaScript “if” statements to validate three date fields separately. This validation required that our all 03 date input fields are in format like dd/mm/yyyy and accept years only 19XX and 20XX. We use match expression technique to implement validation. The following code will be used in Validate function.

 

// check whether 03 date input fields are in valid format i.e. xx/xx/19xx and xx/xx/20xx
    
   re = /^[0-3]?[0-9]\/[01]?[0-9]\/[12][90][0-9][0-9]$/;
    if(myform.dt1.value != '' && !myform.dt1.value.match(re)) {
      alert("Invalid date format: " + myform.dt1.value);
      myform.dt1.focus();
      return false;
	  }

  
    if(myform.dt2.value != '' && !myform.dt2.value.match(re)) {
      alert("Invalid date format: " + myform.dt2.value);
      myform.dt2.focus();
      return false;
	  }


 
    if(myform.dt3.value != '' && !myform.dt3.value.match(re)) {
      alert("Invalid date format: " + myform.dt3.value);
      myform.dt3.focus();
      return false;
	  }

Invoice Form Final Total Value Validation

We have to check that final total in invoice form

1. Should not be zero
2. Final total must be a numeric value

For the purpose following code will be added in Validate function.

 

//Check whether final total is not zero and is a number
	if( document.myform.total.value == "0" )
   {
     alert( "Total Invoice cannot be Zero" );
     document.myform.total.focus() ;
     return false;
   }

   var x=document.myform.total.value;
  
if (isNaN(x)) 
  {
    alert("Please Input Numaric Values for Amount");
       return false;
  }

Most of all above code is written in our validate function which is residing in Javascript_validate.js file and will be called when we press form submit button (as it is in onsubmit event handler of form tag ).

Javascript Validation of amount text field and Auto Total

In this section we are going to add following features in our “invoice_form_validated.php” file.

1. 03 amount fields should accept only numbers and float (decimal) numbers and if we write other than a number then JavaScript should triggered an error message.
2. After entering a number final total should auto add the three values and show final result on the run.

Enter only numbers in Amount text field

To implement this we add 03 more javascript functions in Javascript_validate.js file. These function will be called from onkeyup event handler of 03 price/amount text fields named “prow1”, “prow2” and“prow3”, exists in invoice form. These function check that only number is entered and show final total in the total text field. These three functions are given below:

 

//three function to check price and show total

function only_numbers1() {

var x=document.myform.prow1.value;
  if (isNaN(x)) 
  {
    alert("Must input numbers");
    
  }
  GetTotal();
}




function only_numbers2() {

var x=document.myform.prow2.value;
  if (isNaN(x)) 
  {
    alert("Must input numbers");
    
  }
  GetTotal();
}





function only_numbers3() {

var x=document.myform.prow3.value;
  if (isNaN(x)) 
  {
    alert("Must input numbers");
    
  }
  GetTotal();
}

In all above three function we call a GetTotal function which calculate total from all these three price text fields named “prow1”, “prow2” and“prow3”, in invoice form. We call above three function from the onkeyup Javascript event handler of these text fields. The code on invoice form will look like this.

GetToal() Function

Now we are adding GetTotal() function in Javascript_validate.js file.

 

function GetTotal() {

if (document.getElementById("prow1").value=="")
{  n=0; }
else
{
var n=document.getElementById("prow1").value;
}


if (document.getElementById("prow2").value=="")
{ n2=0;}
else {
var n2=document.getElementById("prow2").value;
}


if (document.getElementById("prow3").value=="")
{ n3=0;}
else {
var n3=document.getElementById("prow3").value;
}


var r=parseFloat(n)+parseFloat(n2)+parseFloat(n3);

document.getElementById("total").value = r;
}

Adding JQuery Calendar in the Date Input Text Fields.

Now we are adding an feature to our invoice web form i.e. JQuery Celandar that will appear when someone click on the date fields. This calendar make it easy to enter date by one click. And it also write date in our desired date format.

First of all we have to include JQuery source file in our invoice form. For that go to JQuery official website and download zip file which hold the full and minified version of jquery source file. We will use minified version of jQuery source file.

Go to JQuery official site and download source zip file

Extract files and copy following file in your invoice form folder:-

jquery-2.0.3.min

If you want more information about jQuery and its usage. You can read my article below:-

Fundamentals of jQuery


Now go to JQuery-UI library website and down JQuery-UI zip file from link given below:-

http://jqueryui.com

extract downloaded zip file and copy following two files in your invoice form folder.

jquery-ui.min.js
jquery-ui.css

to work jquery properly, we have to create another js (javascript) file named “app.js” in invoice form folder and add following code in it:-

 

$(function() {

$( "#dt1" ).datepicker({ dateFormat: "dd/mm/yy" });
 $( "#dt2" ).datepicker({ dateFormat: "dd/mm/yy" });  
   $( "#dt3" ).datepicker({ dateFormat: "dd/mm/yy" });
 
		   });

In this function we are passing three ids of date fields and their formats to jquery to make calendar on click or focus. Be sure that in form, all three date text fields should have ids as given in function like “dt1”,  “dt2” and “dt3” respectively like this:-

 

      <input  class="fileds_container_textbox_onethird" type="text" id="dt1" name="dt1"/>

Now the time we have to include above four files in our main invoice form in its head section. The code will look like this:

 



You can read my detail article on making JQuery calendar

Make a Beautiful Date Picker from a Textbox using JQuery

Now our invoice form validation is complete. The complete javascript_validate.js file will look like this

 

// Javascript validation

//validation check function

function validate()
{
 
    var x = document.myform.return_email.value;
    var atpos = x.indexOf("@");
    var dotpos = x.lastIndexOf(".");
    if (atpos< 1 || dotpos<atpos+2 || dotpos+2>=x.length) {
        alert("Not a valid e-mail in return email field");
		 document.myform.return_email.focus() ;
        return false;
    }
	
	
	
	
	 var x = document.myform.to_email.value;
    var atpos = x.indexOf("@");
    var dotpos = x.lastIndexOf(".");
    if (atpos< 1 || dotpos<atpos+2 || dotpos+2>=x.length) {
        alert("Not a valid e-mail address in forwarding email field");
		 document.myform.to_email.focus() ;
        return false;
    }
	
 
 
 // check whether company name is blank
 
   if( document.myform.to_name.value == "" )
   {
     alert( "Name/Company Field is Blank" );
     document.myform.to_name.focus() ;
     return false;
   }

//check whether at least first description is not blank

 if( document.myform.descrip1.value == "" )
   {
     alert( "Atleast 1 Description is required" );
     document.myform.descrip1.focus() ;
     return false;
   }
   
   //check whether at least one price field is not blank 
   
   
    if( document.myform.prow1.value == "" )
   {
     alert( "Atleast one price should be set" );
     document.myform.prow1.focus() ;
     return false;
   }









// check whether 03 date input fields are in valid format i.e. xx/xx/19xx and xx/xx/20xx
    
   re = /^[0-3]?[0-9]\/[01]?[0-9]\/[12][90][0-9][0-9]$/;
    if(myform.dt1.value != '' && !myform.dt1.value.match(re)) {
      alert("Invalid date format: " + myform.dt1.value);
      myform.dt1.focus();
      return false;
	  }

  
    if(myform.dt2.value != '' && !myform.dt2.value.match(re)) {
      alert("Invalid date format: " + myform.dt2.value);
      myform.dt2.focus();
      return false;
	  }


 
    if(myform.dt3.value != '' && !myform.dt3.value.match(re)) {
      alert("Invalid date format: " + myform.dt3.value);
      myform.dt3.focus();
      return false;
	  }

    //Check whether final total is not zero and is a number
	
	if( document.myform.total.value == "0" )
   {
     alert( "Total Invoice cannot be Zero" );
     document.myform.total.focus() ;
     return false;
   }

   var x=document.myform.total.value;
  
if (isNaN(x)) 
  {
    alert("Please Input Numaric Values for Amount");
       return false;
  }

    return( true );

} //end validation check function


//three function to check price and show total

function only_numbers1() {

var x=document.myform.prow1.value;
  if (isNaN(x)) 
  {
    alert("Must input numbers");
    
  }
  GetTotal();
}




function only_numbers2() {

var x=document.myform.prow2.value;
  if (isNaN(x)) 
  {
    alert("Must input numbers");
    
  }
  GetTotal();
}





function only_numbers3() {

var x=document.myform.prow3.value;
  if (isNaN(x)) 
  {
    alert("Must input numbers");
    
  }
  GetTotal();
}





function GetTotal() {

if (document.getElementById("prow1").value=="")
{  n=0; }
else
{
var n=document.getElementById("prow1").value;
}


if (document.getElementById("prow2").value=="")
{ n2=0;}
else {
var n2=document.getElementById("prow2").value;
}


if (document.getElementById("prow3").value=="")
{ n3=0;}
else {
var n3=document.getElementById("prow3").value;
}


var r=parseFloat(n)+parseFloat(n2)+parseFloat(n3);

document.getElementById("total").value = r;
}

//  ***************************




And  complete code for invoice_form_validated.php is look like this.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Invoice Form Validated</title>

<link rel="stylesheet" type="text/css" href="my_invoice_style.css" media="screen" />
<link href="jquery-ui.css" rel="stylesheet">
<script src="javascript_validate.js"></script>
<script src="jquery-2.0.3.min.js"></script>
<script src="jquery-ui.min.js"></script>
<script src="app.js"></script>

</head>

<body>

              <div id="outer_container">
<form class="form" method="post" name="myform" action="" enctype="multipart/form-data" onsubmit="return(validate());">

   

              <h2>Invoice Form </h2>

     <div id="fileds_container_div">
	 
	 <div class="section_heading">Invoice Info </div>

<div id="heading_over_textbox"> Invoice No. </div>
      <input  class="fileds_container_textbox" type="text" name="inv_no" />
<div id="heading_over_textbox">Invoice Issue Date</div>
      <input  class="fileds_container_textbox" type="text" name="inv_date" />
	  

     <div class="section_heading">Invoice Sender Information </div>

<div id="heading_over_textbox">From  (Individual/Company) </div>
      <input  class="fileds_container_textbox" type="text" name="from_name"/>
<div id="heading_over_textbox">Email Address(Sender)</div>
      <input  class="fileds_container_textbox" type="text" name="return_email"/>

      <div class="section_heading">Invoice Reciever Information </div>
	  
	  
<div id="heading_over_textbox">To  (Individual/Company) </div>
      <input  class="fileds_container_textbox" type="text" name="to_name"/>
<div id="heading_over_textbox">Email Address(Reciever)</div>
      <input  class="fileds_container_textbox" type="text" name="to_email"/>
	  
	    <div class="section_heading">Billing Detail </div>

                 <!--ROW-I of billing widh header title -->  

<div id="fileds_container_onethird">
<div id="heading_over_textbox">Date</div>
      <input  class="fileds_container_textbox_onethird" type="text" id="dt1" name="dt1"/>
</div>
 

<div id="fileds_container_onethird">
<div id="heading_over_textbox">Description</div>
     <textarea  class="fileds_container_textbox_onethird" cols="40" rows="5"   name="descrip1"  /></textarea>
</div>
 
<div id="fileds_container_onethird">
<div id="heading_over_textbox">Amount</div>
     <input  class="fileds_container_textbox_onethird" type="text" onkeyup="only_numbers1();" name="prow1" id="prow1"/>
 </div>
 
<!--ROW-II of billing --> 
 
<div id="fileds_container_onethird">
   <input  class="fileds_container_textbox_onethird" type="text" id="dt2" name="dt2"/>
</div>
<div id="fileds_container_onethird">
    <textarea  class="fileds_container_textbox_onethird" cols="40" rows="5"   name="descrip2"  /></textarea>
</div>
<div id="fileds_container_onethird">
     <input  class="fileds_container_textbox_onethird" type="text" onkeyup="only_numbers2();" name="prow2" id="prow2"/>
</div>
 
<!--ROW-III of billing --> 
 
<div id="fileds_container_onethird">
   <input  class="fileds_container_textbox_onethird" type="text" id="dt3" name="dt3"/>
</div>
<div id="fileds_container_onethird">
    <textarea  class="fileds_container_textbox_onethird" cols="40" rows="5"   name="descrip3"  /></textarea>
</div>
<div id="fileds_container_onethird">
     <input  class="fileds_container_textbox_onethird" type="text" onkeyup="only_numbers3();" name="prow3"  id="prow3"/>
</div>
 
<!--ROW-IV of billing for Total --> 
 
<div id="fileds_container_onethird">
  <!--blank space equal to one box cell--> 	
</div>
<div id="fileds_container_onethird">
   <span style="margin-left:105px;">TOTAL: </span>
</div>
<div id="fileds_container_onethird">
     <input  class="fileds_container_textbox_onethird" type="text" readonly="readonly" value="0" name="total" id="total"/>
</div>

 <input style="background-color:#66CC33;"  type="submit" name="submited" value="Send Invoice"  />


 </form>
 
</div>
</div>
 
</body>
</html>

style.css file is same as in my previous tutorial, you can copy it form there which link I have mentioned in beginning of this tutorial. As this tutorial is at no.2 in series of email invoice sending project. In next tutorial of this series we will learn about making pdf invoice from the information we collect from this invoice form

Leave a Reply

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