Validation

Problem

How to validate data with DHTMLX Touch?

Solution

Data validation can be applied to:

  • DATAPROCESSOR objects.
    Validation is activated: every time when data tries to save to server.
    Please note, validation isn't activated while data loading
    .
  • FORM objects.
    Validation is activated: every time you call the form's method validate().

It's performed by means of the property 'rules' - hash code of the rules (functions) for validated fields.
A code snippet below shows a common structure of the parameter:

rules:[{ control_id:rule}]
  • control_id - the identification name of the control (the value of the parameter id).
  • rule - the appropriate rule for the defined control (can be both a predefined rule or a custom function).

There are three means to set the desired rule:

  1. Predefined expressions.
  2. Custom functions.
  3. Special keys.


Predefined Rules

There are 2 predefined rules expressions:

  • isNotEmpty - checks whether a value is empty.
  • isNumber - checks whether a value is number

    In rules parameter you must refer to them as: dhx.rules.isNotEmpty and dhx.rules.isNumber.

    dhx.ui({ 
                 view:"form", 
                 elements:[{ view:"text", label: 'Name', id: "fname" }],
                 rules:[{ fname:dhx.rules.isNotEmpty}] // the predefined rule 'isNotEmpty'
    });

    Related sample: 02_form/05_validation.html

Custom rules

If you need, you can use any custom function as a rule. Such function will take 3 parameters (btw, value=obj[key]):

  • value - the validated value.
  • obj - the validated data object.
  • key - the id of validated field.

    dhx.ui({ 
    	view:"form", 
            elements:[{ view:"text", label:"Age",  id:"age"}]
    	rules:{age:isPositiveInteger}
    });
    isPositiveInteger = function(value) {return (parseInt(value,10) == value && value>=0);}

    Related sample: 02_form/07_validation.html

Special validation keys: $all and $obj

The keys're used in case you need to validate the whole data object or all set of data.

  • $all - allows to apply some rule to each property of data object.

    var dp = new dhx.DataProcessor({
                 rules:{$all:dhx.rules.isNotEmpty }
                 ...
    });
  • $obj - in this case, a rule will receive the whole data object at once.

    dhx.ui({ 
    	view:"form", 
    	elements:[{ view:"text", label:"Password", id:"pass1", width:200},
                      { view:"text", label:"Confirm password",  id:"pass2", width:200}],
    	rules:{	$obj:confirmPassword }
    });
    confirmPassword = function(obj) { return (obj.pass1 == obj.pass2);}

    Please note, custom validation function for $obj takes the only parameter - a validated data object.

    Related sample: 02_form/08_validation_keys.html