Introduction
Its a simple javascript code.By using this code we can validate web forms using regular expression. The good thing of it, you dont need to write extra code, just put appropriate regular expression in the value attribute of hidden field and make your life easier.
Detail
Idea behind that is, For validating a control of name "text1" u have to add two hidden input fields.One for validation and other for control caption. the name of validation field would be "regex_text1" and the name of caption would be "caption_text1".
Your input control would be validated according to the regular expression which you will write in the value attribute of "regex_text1" input field.
Another thing u have to do is, Call following function on click of a button which you are using for submission.
function ValidateForm()
{
els=new Array();
els=document.forms[1].elements;
for(i=0; i<els.length; i++)
{
var regex="regex_" + els[i].name;
if(els[regex]!=null)
{
var regexValue=els[regex].value;
var elValue=els[i].value;
var re = new RegExp(regexValue);
if(!elValue.match(re))
{
var caption="caption_" + els[i].name;
var captionValue="Field";
if(els[caption]!=null)
captionValue=els[caption].value;
alert("Invalid " + captionValue);
return;
}
}
}
document.forms[1].submit();
}
and your html would be like this.
<input type="text" name="txtSurname">
<input type="hidden" name= "caption_txtSurname" value="Surname">
<input type="hidden" name= "regex_txtSurname" value="^[a-zA-Z]+[a-zA-Z ]*$">
<input type="text" name="txtPostCode">
<input type="hidden" name="regex_txtPostCode" value="^([0-9]+[0-9-]*[0-9]+)?$">
<input type="hidden" name= "caption_txtPostCode" value="Post Code">
<input type="button" name="Submit" value="Submit" onClick="javascript:ValidateForm()">
This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.
A list of licenses authors might use can be found here