Data Validation Using JavaScript

Today we are learning how to correct data sent on respective databases. Data validation is a very important part of Development. Data validation can be applied multiple ways, one is JavaScript and another is the C# language. In this article we are learning how to validate data using JavaScript. We can create any type of validation, for example:

  • Type of Validation
  • Email Validation
  • Phone Number
  • Password
  • Multiple Email
  • Fax number
  • URL
  • User Name

Why to use JavaScript Validation

JavaScript Validation

JavaScript is working in every browser and it's working on the Client Side. When we request a page like this page JavaScript stores in the web browser local storage. if you want more information about local storage in Firefox click here. JavaScript is stored in a DOM object. This is temporary storage for JavaScript. When the page goes away the browser automatically removes the JavaScript. Here is one look at how JavaScript works.

Note: If you want to use a debugger in JavaScript then simply press the function key "F12". A window will pop up after a bit. If you want more information about debugging JavaScript then click here.

In the following image you can see the password holds the value "dfgaadfaad" but Email and first name is empty because I have not entered the value in email and the first TextBox.

js code

Note: I have used Firebug for showing data in JavaScript. If you want to download Firebug the then go to this link; it's free of cost.

In this article it is not possible to show every type of validation. I have used one validation for a Valid URL. Mostly when I add the URL on any web form, I get confused about forward and backward slashes.

Here is one example of validatating an URL:

  1. var tempUrl = value.match(/^(http(s)?:\/\/)?([A-Za-z0-9][\w-]*[A-Za-z0-9]\.)+[A-Za-z]{2,3}(\/[\w- .\/?%&=]*)?$/g)    
  2.                 if (value != tempUrl)    
  3.                     return false;   
I check the client-side URL and I enter You can see the following check for how to work with JavaScript. You think the preceding and this picture are different. Of course it's different, the preceding image was captured by Firebug and the following image is from Google Chrome Developer Tools.

script code

Email Validation
  1. var tempMail = value.match(/^\w[\w\.\_\-]*\w\@\w[\w\-\.]*\w\.[a-zA-z]{2,3}$/g)    
  2.                 if (value != tempMail)    
  3.                     return false;   
  1. var validChars = ", +-0123456789";    
  2.         for(i=0;i < value.length;i++)    
  3.             if(validChars.indexOf(value.charAt(i)) == -1)    
  4.                       return false;    
I hope everyone understands what I am trying to say. Comments are most welcome.


Up Next
    Ebook Download
    View all
    View all