How to Validate Fields Before Submitting a Form

The standard field validation validates a field when the form is submitted, but it is possible to extend this capability to the blur event for the field (as soon as the user leaves the field). This is done by leveraging the K('field['+fieldName+']').validate() function and the jQuery blur function (set up on the page load) for the appropriate object (field).

In this example, we will be validating an IP address field, and using notifie library to display an error if the pattern of the field doesn't validate when the user leaves the field, as well as on submit time.

  1. Set up the field with the desired validation.

In this case we are setting up a pattern for the IP Address field.

  1. Give the field an appropriate Render Attribute so there is a specific class on that field.

In this case we are using a class called ipaddress.

  1. Add the load event to extend the validation to blur for that field.

$('.ipaddress').blur(function(){ //find the field name for this field var fieldName = $(this).attr('name'); //run validation for this field var errors = K('field['+fieldName+']').validate(); //loop through any errors found if(errors.length > 0) { //display the errors with the field errors.forEach(function(message){ $(K('field['+fieldName+']').element()[0]).notifie({ type: 'alert', severity: 'danger', message: message, expire: 500, exitEvents: 'click'}); }) } });

This calls the validation function for the field with that class and displays the error messages for any errors it finds.