Aaron Newton has released some new form validators (with help from contributor Chafik Barbar) and documentation for his beta code. Everyone has to deal with form validators one way or another. I\’ve posted on one from MooTools.Floor, but this is a different way of doing things.
The FormValidator / InputValidator Code
There are two ways to set up form validators. The first is to use InputValidator.
This class contains functionality to test a field for various criteria and also to generate an error message when that test fails.
It takes two arguments, the class name that is applied on the element and options to test against and errorMsg to display.
//html code
//simple validator
var isEmpty = new InputValidator(\'required\', {
errorMsg: \'This field is required.\',
test: function(field){
return ((element.getValue() == null) || (element.getValue().length == 0));
}
});
isEmpty.test($(\"firstName\")); //true if empty
isEmpty.getError($(\"firstName\")) //returns \"This field is required.\"
Then there\’s FormValidator.
Evalutes an entire form against all the validators that are set up, displaying messages and returning a true/false response for the evaluation of the entire form.
You can set it up with custom validators using the arguments you would in InputValidator too, for all instances of the FormValidator or just the instance of the FormValidator.
//add a validator for ALL instances
FormValidator.add(\'isEmpty\', {
errorMsg: \'This field is required\',
test: function(element){
if(element.value.length == 0) return false;
else return true;
}
});
//this validator is only available to this single instance
var myFormValidatorInstance = new FormValidator(\'myform\');
myFormValidatorInstance.add(\'doesNotContainTheLetterQ\', {
errorMsg: \'This field cannot contain the letter Q!\',
test: function(element){
return !element.getValue().test(/q/,\'i\');
}
});
At first glance, I didn\’t really like this setup of the form validator. It felt clunky; I would have to create many custom validators. But I realized you can add custom validators globally or for instances and I wouldn\’t have to re-build them again. I think this is actually smaller than MooTools.Floor\’s validator.
Thank you, Aaron and Chafik. Now we\’ll know how to use/test the beta code and we won\’t have to write extra validators. 😀