Javascript Form Field Validation

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
papa_smurf
Forum Newbie
Posts: 14
Joined: Tue Jun 01, 2010 12:22 pm

Javascript Form Field Validation

Post by papa_smurf »

Hey all,

I want to be able to validate a text field in a form after the user fills it in as he/she moves to the next text. I would like the js file to be able to read the name of the text and tell wether the information for that text has been filled in correctly.

For instance I have two text fields named "F" and "B" respectively. The "F" field is first and the "B" field is second. What I would like is as the user finishes the first field and moves to the second field, the program will check what fields have been filled in, if they have been filled in, then it will check to see if the correct information is in it. In this case it would check to see that there are only 3 numbers in field "A".

Is there anyway to do this? I'm still new to javascript so I don't know.

Thanks!
User avatar
kaszu
Forum Regular
Posts: 749
Joined: Wed Jul 19, 2006 7:29 am

Re: Javascript Form Field Validation

Post by kaszu »

Add "blur" event listener to input, it is triggered when input looses focus. And on callback (function which is called when event is triggered) check if value length is 3 caracters.
See addEventListener (also read this).

Code: Select all

<input type="text" name="F" id="inputF" value="" />

Code: Select all

//get input node by "id" attribute
var input = document.getElementById('inputF');

//Add event listener (using cross-browser version writen by PPK, link above)
addEventSimple(input, 'blur', function () {
    //In event listener "this" keyword refers to input
    if (this.value.length != 3) {
        //Do something if not 3 characters
        alert('Not 3 characters');
    }
});
papa_smurf
Forum Newbie
Posts: 14
Joined: Tue Jun 01, 2010 12:22 pm

Re: Javascript Form Field Validation

Post by papa_smurf »

Perfect, Much thanks!
Post Reply