Kauri Documentation
 PreviousHomeNext 
10.3.1 Custom FormattersBook Index10.4 Forms Reference

10.3.2 Custom Validators

Responsibility

Validators are there for validating the input of end-users.

The ' field section' of the Form Concepts page explains where those validations fit in.

Validators have various events to report validation progress and results to the control holding the validator.

Coding

The framework offers a base class to start your own validator from.  Its main advantage that your only need to implement a validation method and return the validation status using calls to notifySuccess() or notifyFail(msg)
The anonymous function construct is a technique to ensure no top level naming conflicts will occur. The variables we declare form a shorthand for the namespaces relevant for Kauri.

;
( function( $) {

    var kf = $.org.kauriproject.forms;
    var validators = kf.validators;
    kf.validators.putAll( {
      "isPrime": { "validate": function(value) { 
        var primeFunc = function(n,f) {
          f = f || 2;
          if (n == f) return true;
          if (n%f==0||n==1) return false;
          return primeFunc(n, f+1);
        };
        if (primeFunc(value)) {
          return this.notifySuccess();
        } else {
          return this.notifyFail("That is not a prime number");
        }
      }}
    });
})(jQuery);
Declaring

Alternatively the validator can be specified inside the form-config by placing it in the 'validators' section. In that case the behaviour of the described base class will be automatically applied to it, allowing you to leav out quite some boiler-plate code:

Assuming the dafult format() is ok, you could deal with it like this:

var fconf = {
    ...

    'validators':    {
        'isPrime' : {
            'validate': function(valstr) {
                   // implementation here, including calls to this.notifySuccess() and this.notifyFail(msg);
            }
        }
    }
}
 PreviousHomeNext 
10.3.1 Custom Formatters10.4 Forms Reference