Click here to Skip to main content
Click here to Skip to main content

Form Validation with Regular Expression Short Version

, 31 May 2007
Rate this:
Please Sign up or sign in to vote.
Validate form controls with the use of a regular expression outside the function.

Introduction

This is a short and simple form validation code that uses regular expression to compare the user input to the pattern rule defined by a regular expression string. form validation code will either use "if" statments, or regular expressions to validate that the user entered the currect information .

The main difference between this code and others , is that the regular expression pattern, and the error message, both are located inside the html control tag and not in the function itself. The advantage is that you don't need to mess with the function to change a specific condition or validation rule, you simply need to enter the rule in the html tag under the validate attribute. The disadvantage is redundancy, if you have three fields in a form that needs to implement the same rule, you will still need to rewrite the regular expression on each of those control. I hate redundancy as everybody else, but I think that in this particular code it is not a high price to pay for a generic function.

The Code

The function goes over the form elements searching for a "validate" attribute and tries to mach the regular expression value of the attribute with the user input. If the user input doesn't comply with the regular expression pattern the function will raise an error alert. In other words, the content of each form-element with the attribute "validate" will be evaluate by the function to check if it follows the regular expression rules

  1. The function receives the from as an object.
    function checkForm(formObj){
  2. The variable msg is initialized to an empty string. Any data not matching the regular expression will invoke the code to collect the error description into this variable. So all the errors on the form will be presented to the user together in one alert rather then separate alerts for each error.
    var msg="";
  3. Loop through the form elements.
    for (var i=0; i < formObj.elements.length; i++) {
  4. Check if the element has a name, and a validate attribute.
    if (formObj.elements[i].name !=null && formObj.elements[i].getAttribute("validate")){
  5. Evaluate the regular expression from the element validate attribute.
    var validationRule = eval(formObj.elements[i].getAttribute("validate"));
  6. If a mismatch was found, then add the error description from the control tag validateMsg attribute to the msg variable.
    if (!validationRule.test(formObj.elements[i].value))
    var obj = formObj.elements[i].parentNode;
    // add a * mark on the validate field – this part is not mandatory and can be removed.
    if (obj.nodeName=="TD")
    { obj.innerHTML = "!!!"+ obj.innerHTML; }
    msg += formObj.elements[i].getAttribute("validateMsg")+"\n";
    !! end the loop
  7. If the msg variable is not empty it means that errors were found. Present the errors and return false.
    if (msg.length > 0){ alert (msg); return false; } else{ return true; }
        function checkForm(formObj){
        var msg="";
        for (var i=0; i < formObj.elements.length; i++) {
               // check if the form element has a validate attribute. 
               if (formObj.elements[i].name !=null && 
                 formObj.elements[i].getAttribute("validate")){
                 var validationRule = 
                   eval(formObj.elements[i].getAttribute("validate"));
                   if (!validationRule.test(formObj.elements[i].value)){ 
                    var obj = formObj.elements[i].parentNode; 
                   // add a !!! mark on the validate field 
                    if (obj.nodeName=="TD")
                     obj.innerHTML = 
                       "<span style='color:red;'>!!!</span>"+ obj.innerHTML; 
          msg += formObj.elements[i].getAttribute("validateMsg")+"\n"; 
                   }//--> end test regExp
                 }//--> end if element has validate attribute
                }// end loop through the form elements. 
               if (msg.length > 0){
                 alert (msg);
                 return false;
               }
                 else{
                  return true;
                 }
            }//--> end function 

Code Implementation

In order to use the code follow these steps:

  1. Copy the code to your page between the <script></script> tags or create a JS file and link it to your HTML page.
  2. In the form tag add the method to the onclick event: <form method=post name=myForm onsubmit="return checkForm(this);">
  3. At each html control you would like to validate add the validate attributes and the errDescription attributes: <input width=100 type=text validate="/^([\w]+)(.[\w]+)*@([\w]+)(.[\w]{2,3}){1,2}$/" name=email id=email validateMsg="not the right format">

Some regular expressions:

  • validate="/[\d\w]{3,}/" - the data must be at least 3 characters long and should include letters or digits
  • validate="/^([0-9]{11})$/ " - Phone number with 11 digits.
  • validate="^([0-9]){2}(\/|-){1}([0-9]){2}(\/|-){1}([0-9]){4}$/" – Date in the format dd/mm/yyyy
  • validate="/^([\w]+)(.[\w]+)*@([\w]+)(.[\w]{2,3}){1,2}$/" – Email

License

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

Share

About the Author

alfi uziel
Web Developer
United States United States
web developer,
windows based applications ,
data specialist.
java,c#,asp,jsp,vb

Comments and Discussions

 
QuestionLicensing PinmemberLucky#715-Jul-08 12:37 
AnswerRe: Licensing Pinmemberalfi uziel15-Jul-08 18:52 
GeneralRe: Licensing PinmemberLucky#716-Jul-08 2:55 
GeneralRe: Licensing Pinmemberalfi uziel16-Jul-08 16:27 
Questionusing regular expression to validate required and email at same time? PinmemberAmer Azzaz13-Mar-07 6:08 
AnswerRe: using regular expression to validate required and email at same time? Pinmemberalfi uziel13-Mar-07 8:51 
GeneralRe: using regular expression to validate required and email at same time? PinmemberAmer Azzaz14-Mar-07 0:24 
GeneralRe: using regular expression to validate required and email at same time? Pinmemberalfi uziel14-Mar-07 8:27 
GeneralThanks PinmemberDileep.M8-Mar-07 0:01 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.150123.1 | Last Updated 31 May 2007
Article Copyright 2007 by alfi uziel
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid