Individual Field Validation
Join the Discussion
When you have text fields on your form (or drop down lists that include invalid values) it can make sense to validate the field immediately after the field has been updated rather than waiting until the entire form has been filled out. By doing this the person filling out the form can know immediately that the value that they have entered is invalid allowing them to correct their entry before filling out the rest of the form. In some cases telling them that the first field is invalid straight away may let them know that they are filling out the wrong form before they waste time filling out all of the fields.
We can validate text fields straight away using the onblur event handler. When we add this event handler to our text fields and text areas the appropriate validation routine will be called as soon as the person moves on to another field.
Of course we will still need to validate the same field immediately prior to submitting the form just in case someone bypasses accessing the field at all. We can easily add the same validation to both places by placing all of the code for the validation into a function and calling that function from both places.
Here is what the code for a text field looks like with the validation processing added:
In this example the field is presumably expected to contain an email address and the function validateEmail is being called to perform the validation. The value of the input field itself is being passed as the first parameter and can always be referenced in this situation as this.value as the onblur event is attached to the field whose value is to be passed. The other parameter that need to be passed will usually be fixed values that help define how the particular field validation is supposed to function.
If you have a textarea that you want to validate immediately after the person filling out the form moves on to the next field then you can perform the validation function the same way as you do for a text input field by adding an onblur event handler to the textarea tag.
You can validate a dropdown list even earlier in the process. By adding an onchange event handler to the select tag we can validate the field as soon as the person has selected an entry in the drop down list. We don't need to wait until they move to another field (and thus trigger the onblur event) before we validate it.