Share the ideas and thoughts, become united ...

Saturday, April 3, 2010

Code n Learn: Form Validation Javascript

We all know that it is the programmer's duty to validate the form against invalid inputs. This checking or validation can be down in two ways. One is Client side, other is Server side.

We will have a quick review on how to validate form in client side using javascript.

Let us consider we have a form with first name, last name, email address and comment.

<form action="submit.php" method="post">
    First name: <input type="text" id="fname" value="" name="fname" /><br />
    Second name:<input type="text" id="lname" value="" name="lname" /><br />
    Email: <input type="text" id="email" value="" name="email" /><br />
    Comment: <input type="text" id="com" value="" name="com" /><br />
     <input type="submit" value="Submit" name="submit" onclick="return validate()" />
</form>
Ok, you may wonder why we add the id to all of the input type? Ids must be unique and we can search a component by its Id. So, we need to have an Id for each field which we will validate.
On the submit button we added onclick="return validate()". Here validate() is the form validation function. Then why we use return in front of it? Its because if the function return false then the form wont be submitted, It will be submitted once it receives true from validate function.

Now we add some basic style using CSS (Cascading Style Sheets). We only need two classes. One when there is a validation failed, other one is when validation is successful.

.error {
    background-color:rgb(255,0,0); /* red color */
}

.valid {
    background-color:rgb(0,255,0);  /* green color */
}
 We assign the error class when validation fails, thus making the component go red indicating an error was detected. You can run you imagination wild when customizing the class. We assign the other when validation success.

Now we only require the validation function to validate the form.
We need to get the handler of the First name & Last name text box. This can be done by searching the element by document.getElementById() function. Then we check the value entered by the user using the value property of that component.
function validate_component(name) {
     var comp = document.getElementById(name);
     if (comp.value == null || comp.value == '' ) {
         comp.className = 'error';      /* assign the css class to this component to indicate validation failure */
         return false;
     } else {
         fname.className = 'valid';    /* valid */
         return true;
     }
}
 We have setup the basic validation method. With this method we can validate first name, last name and comment component. We need to consider the email validation case. Cases to be considered when validating an email are -
  1. Email must have one '@' [at] and at least one '.' [dot]  ( xyz@yyy.ccc )
  2. '@' [at] cannot appear as first element  ( @xyzyyy.ccc )
  3. '.' [dot] cannot appear as last element  ( xyz@yyyccc. )
  4. Last '.' [dot] must be after '@' [at] but not immediate after ( x.y.z@yyy.ccc | x.y.z@.yyyccc )
  5. There can be exactly one '@' [at]
 Now the validation

function validate_email() {
    var error_occured = false;
    var e = document.getElementById('email');
    var email = e.value;
    error_occured = !validate_component('email');   /* check for basic validation */
    var at_index = email.indexOf('@');      /* returns the index of @  or -1 indication there was none */
    var at_last_index = email.lastIndexOf('@');
    var dot_index = email.lastIndexOf('.');
    if ( at_index == 0 || at_index == -1 || at_index != at_last_index || dot_index <= at_index || dot_index - at_index == 1 || dot_index == -1 || email.length - dot_index == 1 ) {
         error_occured = true;
         e.className = 'error';
    } else {
         e.className = 'valid';
    }
    return !error_occured; 
}
 What does what :
  1. at_index == 0 [ '@' was the first element so invalid ]
  2. at_index == -1 [ '@' was not found ! ]
  3. at_index != at_last_index [ There were more than one '@' (invalid) because first @ and last @ have different index number ]
  4. dot_index <= at_index [ '.' was infornt of '@' (invalid) ]
  5. dot_index - at_index == 1 [ '.' was immediately after '@' (invalid) ]
  6. dot_index == -1 [ '.' not found ! ]
  7. email.length - dot_index == 1 [ '.' is the last element (invalid) ]

Now we are ready to integrate all of this to one function.

function validate() {
            /* evaluate values */
    var ev_f_name = validate_component('fname');
    var ev_l_name = validate_component('lname');
    var ev_com = validate_component('com');
    var ev_email = validate_email();
    if ( ev_f_name && ev_l_name && ev_com && ev_email ) {
           return true;
    } else {
           alert('Please fill the form completely and correctly');
           return false;
    }
}
Here you go. The validation is complete. Hope you find it useful. If any suggestion or question please leave a comment.

2 comments: