We have several fields that require validation in Javascript. Each field has several conditions to validate. For example, field x is mandatory, is an integer, and can only be 1, 6, or 9.
A few ideas:
-
Create an object for each field with properties for mandatory, data type, and an array of valid values. Create functions to validate all aspects of the class based on an input. The problem is that not all validations are identical and it would require data entry for each input field.
-
Create parallel arrays with validation information stored inside, possibly using 2D arrays for the valid values. Loop through all form data where the ID matches an array index and then run generic code to validate based on array values.
-
Run through each and every field with IF statements the hard but simple way =(
Any thoughts?
I highly recommend jQuery Validate.
It’s a jQuery plugin that does all (and more) of what you’ve listed.
It does, however, depend on jQuery.