validating forms
form validation is a common task for most any web developer. if you accept and store data entered by users into a form on a web page, a little bit of javascript can go a long way to keep your data clean, by helping users enter correct data in the first place.
start with some form:
<form name="my_form" action="/submit/action" method="POST">
<input validate="number;length:4,4" type="text" name="year"/>
</form>
say for example you want an input field to only accept 4 numeric digits, and anything but that will show the user an error. you may not recognize the validate attribute on the input field-- today i wrote a little bit of javascript that reads whatever value is in there and uses that to validate that field.
var validator = new Validator();
var filter = new Filter();
var validate = function() {
var valid_spec = $(this).attr('validate');
var filters = $(this).attr('filters');
if (filters) {
$(this).val(filter.filter(filters, $(this).val()));
}
if (!validator.validate(valid_spec, $(this).val())) {
$(this).addClass('ui-state-error');
return false;
} else {
$(this).removeClass('ui-state-error');
return true;
}
};
$('[validate]').blur(validate).change(validate);
using a little jquery magic, and a couple of utility functions that do the actual validation (and some filtering) for us, this is all it takes to do some nifty javascript validation on any form, simply by specifying the "validate" attribute on any input field.
you can check out or download those utility functions here: Validator.js