I’ve been busy playing with some JavaScript in these last few days. One of my projects was to create a form-validation similar to the one Remember The Milk has for creating new users. So validator.js was born. You can easily spot the born-on-RTM’s-functionality in the fact that the valid/invalid images I use are directly stolen from RTM. Sorry guys, I’m not the creative type.
Of course, a JavaScript ain’t worth much without a showcase. So here it is: http://sevengoslings.net/validator.js/testform.html
It quite simply works by creating an instance of the Validator class and calling apply() on said instance:
window.onload = function() {
new Validator( 'id-of-your-form', 'class-name-of-your-row-elements', 'class-name-of-your-hint-element').apply();
}
You then add a ‘validator‘ attribute to your input element with the name of the validator you need to apply to the field. Currently I only have 3 different validators.
Ohh, and important. Remember to include Mootools first. That is a requirement for it to work.
But when are you guys ever happy with a one-size-fits-all approach to silly JS functionality? So queue inspirational music and much ado about nothing. Here comes the configurability.
setImages: The method setImages( validSrc, invalidSrc, widthInt, heightInt ) allows you to change which images to display.
setEventsToMonitor: The method setEventsToMonitor( eventsArray ) allows you to change which events will call the runCheck() check on the field. So if you only want it to check onblur, just supply ['blur'] as the parameter.
addValidator: If you feel like my default validators aren’t worth two pennies, you can add more with the function addValidator( nameString, validatorObj ). Just supply a name and a object with the two functions: valid(value) and hint().
Of course all these functions will return itself so you can chain them together to avoid multi line setup. Because I hate those.
-fangel
April 8th, 2007 | JavaScript