06
Abr

Code tip: Add custom validation to form fields

  • Font size: Larger Smaller
  • Hits: 16113
  • Print

Simple validations (required fields, max and min values for a numeric input..) can be configured at your input field properties, the form will add the needed validation functions and messages.

You have also available some default classes that you can apply to your input fields in order to perform validations, you only need to write the class name at the css class property of your field. This is the list of default validation classes you can use:

 

Check the following video in order to see how to configure simple validations and customize your input fields

Each form has very specific requirements, and sometimes you will need to add any custom validation that is not present at the default set. The calcbuilder module includes the jquery validator, so you can extend the default validations adding any custom functions. New validations are created using the first javascript tab of the calculator 'executed on loaded page', and then are attached to the fields placing the name of the new validator function at the 'Css class' of the field.

We're going to create a new example validator, we have two fields at our form, number1 and number2, both typed as numeric. We want to add a new validation because we want to validate number2 is greater than number1 before launching calculations. We are going to call our new validator 'cb_greaterthan'. It will compare the value of the field with the value existing at 'number1' field.

For this example, this is the code you should add to the first javascript tab of the calculator 'executed on loaded page':

//new validator function

CB.validator.addMethod("cb_greaterthan", function(value, element, params) {

//we recover the value at number1 field

var valueinit=CB("input[fldname=number1]").val();

//if value of the field or value of number1 is empty the validation won't pass

if (value==''||valueinit=="") return false;

//we compare the two values and return if value is greater than number1

value=parseFloat(value);

valueinit=parseFloat(valueinit);

return value>valueinit;

//Replace here the error message for the preferred one

}, CB.validator.format("Value must be greater than number1"));

//We attach the validator to the fields with css class 'cb_greaterthan'

CB.validator.addClassRules({ cb_greaterthan : { cb_greaterthan : true } });

Now you can add this validation to the second field (number2, or to any other), this is done at the 'field configuration'. Add
cb_greaterthan
to its 'Css class' field, and you will see the validator launches this function, and places the error message if the field doesn't pass the validator condition.

Last modified on
Trackback URL for this blog entry.

Lo que nuestros clientes opinan de nosotros