Bring Your Forms to Life With Javascript [con't]
Creating a JavaScript Validation Object
The best way to create reusable validation is to create an object. This object will need to validate whether a required field has been completed, the required length of a field has been reached in cases where necessary, such as a zip code and to make sure email addresses are formatted properly. When all fields are completed and these conditions have been met we'll enable the submit button for the form, otherwise we leave it disabled to prevent any errors from occurring.
In order to set all of the properties the object we create an method called Initialize
that receives the following parameters: formId
, fieldNum
, submitId
, validImage
and invalidImage
. The formId
is the id of the form we're validating; this will enable us to target it at a later date. The fieldNum
is the number of required fields in the form. The submitId
is the id of the submit button, to be enabled when all required fields have been successfully validated. The last two are image paths to custom images for valid and invalid fields. The images defined in in these parameters will be inserted in the page next to a field when validated, but you can always change the placement at a later date depending on your design.
The next method in the Validator object is Validate
, which take selector and inputType
parameters. The selector is the form element to be validated and the inputType
is an optional parameter to handle special fields, such as an e-mail, Web address or any other type of field that would need custom validation. This is where validateEmail
comes into play, which handles validating e-mails specifically. In both of these methods, once the field has been validated one of two methods are called, valid or invalid, based upon whether the field was successfully completed. The valid method inserts the valid image, which was defined in the Initialize
method, next to the current field being validated. It then increases the property called fieldNumValidated
, in order to keep track of how many fields have been validated and how many are left before the submit button is enabled, if this condition is true than the submit button is enabled. The other two methods are fairly self-explanatory. Preload
preloads the valid and invalid images for the current selector when the Validate
method is called, this helps the image show up faster when called upon and the AllFieldsValidated
method is a handy method to check on whether all fields have already been validated.