I use the LiveValidation Javascript library to handle most of my client-side form validation features. With it, fields are validated as the user types and instant feedback provides the user with specific instruction on how to correct errors – BEFORE they get to the server and database. The documentation for the library (see link above) is complete and provides lots of examples.
The process for defining a validation rule involved creating a LiveValidation object instance for each field (by ‘id’), then adding the types of validation rules you’d like to use for that object/field element.
This code creates the validation object instance and a ‘Presence’ (field contains something) validation rule for the HTML element with id = ‘txtFirstName’.
var valFirstName = new LiveValidation('txtFirstName'); valFirstName.add(Validate.Presence);
However, if you have a large form with numerous fields – it becomes a tedious task to create all of the objects and basic ‘Presence’ validation rules.
To reduce some of the time required, reduce errors and omission, and improve the efficiency of the code, I’ve created a simple solution that automatically creates the object instances for all of the selected elements on the page, along with the ‘Presence’ validation rule.
This snippet of jQuery code will select all <input type=”text”> elements on the form, create a LiveValidation object instance for the element (as element in the txtElements array, using the id as the index), and add a ‘Presence’ validation rule.
//add LV object and Presence validation to all input:text elements on form var txtElements = {}; $(':text').each(function(){ idElement = $(this).attr('id'); txtElements[idElement] = new LiveValidation( idElement ); txtElements[idElement].add(Validate.Presence); });
If you would like to add additional rules to the objects created, you may do so by referring to the object in the txtElements array – using the HTML element ID as the index. For instance, the following adds extended validation rules to specific input fields:
//additional validation txtElements['txtStudentDOB'].add(Validate.Date2); txtElements['txtStudentEmail'].add(Validate.Email); txtElements['txtStudentPhone'].add(Validate.PhoneNA); txtElements['txtParentEmail'].add( Validate.Email ); txtElements['txtParentPhone'].add( Validate.PhoneNA ); txtElements['txtEmergPhone'].add ( Validate.PhoneNA );
Of course, you may also selectively remove validation that may have been added in the bulk process, but not desired by using the destroy() method of the LiveValidation class.
txtElements['txtDoNotValidateThisField'].destroy();
I hope this simple process makes the validation process easier for your forms and saves you time in development and debugging.