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.
<BLOCKQUOTE dir=ltr style="MARGIN-RIGHT: 0px">
<P>function ValidateForm()<BR>{<BR> els=new Array();<BR> els=document.forms[1].elements;<BR> for(i=0; i<els.length; i++)<BR> {<BR> <BR> var regex="regex_" + els[i].name;<BR> if(els[regex]!=null)<BR> { <BR> var regexValue=els[regex].value;<BR> var elValue=els[i].value;<BR> var re = new RegExp(regexValue);<BR> if(!elValue.match(re))<BR> {<BR> var caption="caption_" + els[i].name;<BR> var captionValue="Field"; <BR> if(els[caption]!=null)<BR> captionValue=els[caption].value;<BR> alert("Invalid " + captionValue);<BR> return; <BR> }<BR> } <BR> <BR> <BR> <BR> }<BR> document.forms[1].submit();</P>
<P>} </P></BLOCKQUOTE>
<P dir=ltr>and your html would be like this.</P>
<BLOCKQUOTE dir=ltr style="MARGIN-RIGHT: 0px">
<P dir=ltr><input type="text" name="txtSurname"><BR> <input type="hidden" name= "caption_txtSurname" value="Surname"><BR> <input type="hidden" name= "regex_txtSurname" value="^[a-zA-Z]+[a-zA-Z ]*$"></P>
<P dir=ltr><input type="text" name="txtPostCode"><BR> <input type="hidden" name="regex_txtPostCode" value="^([0-9]+[0-9-]*[0-9]+)?$"><BR> <input type="hidden" name= "caption_txtPostCode" value="Post Code"></P>
<P dir=ltr><input type="button" name="Submit" value="Submit" onClick="javascript:ValidateForm()"></P></BLOCKQUOTE>