Page 1 of 1

Javascript Form Field Validation

Posted: Wed Jun 02, 2010 2:08 pm
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!

Re: Javascript Form Field Validation

Posted: Wed Jun 02, 2010 4:29 pm
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');
    }
});

Re: Javascript Form Field Validation

Posted: Thu Jun 03, 2010 10:29 am
by papa_smurf
Perfect, Much thanks!