10.3.2 Custom Validators
Responsibility
Validators are there for validating the input of end-users.
The '
Validators have various events to report validation progress and results to the control holding the validator.
- validationStart
- validationFail
- validationSuccess
- validationComplete
- validationIgnored
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);
}
}
}
}
Previous