Updating ‘validate-one-required’ in Prototype.js Dexagogo validation
June 18th, 2008
Dexagogo Validation ala prototype.js Hasn’t been updated for over a year now, but there was one validation that always bugged me:
validate-one-required*
*To use the validate-one-required validator you must first add the class name to only one checkbox/radio button in the group (last one is probably best) and then place all the input elements within a parent element, for example a div element. That way the library can find all the checkboxes/radio buttons to check and place the validation advice element at the bottom of the parent element to make it appear after the group of checkboxes/radio buttons.
The problem with this? As coded, all inputs must be direct descendants of the same parent. Browsers, however, do not have any such restriction; as long as the element names are the same, they can be anywhere in the form.
As of 1.5.4.1, the code is:
['validate-one-required', 'Please select one of the above options.', function (v,elm) {
var p = elm.parentNode;
var options = p.getElementsByTagName('INPUT');
return $A(options).any(function(elm) {
return $F(elm);
});
}]
I’ve replaced it with the following (Tested in Prototype 1.6.0.2)
['validate-one-required', 'Please select one of the above options.', function (v,elm) {
var options = elm.up('form').descendants().collect( function(s) { if (s.tagName == "INPUT" && s.name == elm.name) return s; }).compact();
return $A(options).any(function(elm) {
return $F(elm);
});
}]
Stepping through that long selector:
- Get the radio/checkbox input
- Find the form that contains it
- Get every non-text element in that form
- Out of those, find all <input> tags with a matching name
- Filter out everything that didn’t match (which shows up as undefined)
The message will still show up after the item with the class ‘validate-one-required’, which should probably be the last one. However, now your radio/checkbox inputs can be in whatever markup structure you want.
-Sud.
Posted in JavaScript |
July 1st, 2008 at 4:06 am
Thanks for the bugfix, now it’s working!!