Validation Form

A program in Java Script to demonstrate general validation using regular expression in Java Script.


Validation is an important part while building a website or general page since it helps us validating  the entered data from the users and reporting any errors. This helps us gathering proper data rather than garbage.

Now validation can be done in different methods  or at different stages but it here are few simple ones.


In this example program below the validation rules for:
Name - should start with a capital letter and can have any number of words but should start with capitals.

RollNo - It should have a basic number as "12103158" in the start and can have number ranging from 1 to 68.


Program:

The screen shot of the html program
 

function nameVal()
{
 nm=document.getElementById("un").value;
 if(nm.search(/^[A-Z][a-z]+( [A-Z][a-z]+)*$/)==0)
   alert("valid name");
else alert("invalid name");
}
 function rollVal()
{
 r=document.getElementById("r").value;
 if(r.search(/^12103158(0[1-9]|[1-5][0-9]|6[0-8])$/)==0)
 alert("correct rollno:");
 else
alert("invalid rollno");
}

Explanation for the program:


In the program the "onchange " event is used for the test box saying that on change of data in the text box call a function. 
In the JavaScript we use regular expressions for searching and the keyword "search" is used. The search function returns the location of the first letter of the entry where it satisfied the regular expression. since in our case we need it to start with caps and we have only one name we tried to satisfy the condition with comparing the return value with Zero.

Screen shot of the html page.


And when your enter something and it is not according to the validation rules it displays an alert.
screen shot showing an alert message displayed by the browser.







Comments

Popular posts from this blog

Refrigeration By ice cutting.

How to check if you're buying a stolen phone.

Life after Chernobyl