Unobtrusive Field Validation
After reading the code at tetlaw’s blog, I immediately thought this was most applicable to our current codebase.
Currently the RHTML template forms that we have use this form
<div class="required">
<label for="query">Search</label>
<input id="query" name="query" />
</div>
So what seems to be the problem here? Andrew Tetlaw’s validation library assumes that CSS class names are attached to the field in question. Modifying the existing codebase, with literally hundreds of fields would be out of the question.
So how do you go about doing this using his library? An attempt at hacking one of the functions would be:
Validation.validate = function(elm, options){
options = Object.extend({
useTitle : false,
onElementValidate : function(result, elm) {}
}, options || {});
elm = $(elm);
var cn = $A(elm.classNames()).concat($A(elm.parentNode.classNames()));
return result = cn.all(function(value) {
var test = Validation.test(value,elm,options.useTitle);
options.onElementValidate(test, elm);
return test;
});
}
I just changed the line
var cn = elm.classNames();
to
var cn = $A(elm.classNames()).concat($A(elm.parentNode.classNames()));
This now matches our current XHTML form coding standard. In a way this is akin to rails plugins having the similarity of injecting different behavior to functions at runtime.