I ran into an interesting problem recently dealing with some complicated form validation. The issue was that we had several forms with fields that were required or optional based on if other inputs were filled out, with the requirements falling in a specific order. I came up with an interesting solution that looks at a data-ignore-validation attribute on the current form element and, if it exists will check the form element(s) with that name to see if they are filled out, or if they have a similar data-ignore-validation attribute meaning they can possibly be ignored as well. We have a nice little recursive solution that will check all of the form elements in a chain to see if the current one can be ignored.
All we need to do is send the following function the form element to be checked as well as our form, and it will tell us if the element passed in should be ignored.
[sourcecode language=’javascript’]
function ignoreField(elem, form) {
//if we have an data-ignore-validation property, we can ignore _this_ .val() if the field with the name = ignore-validation has a .val() set
var ignoreOn = $(elem).data(‘ignoreValidation’);
if(ignoreOn) {
ignoreOn = ignoreOn.split(‘,’);
//We use this var to hold the complete list of for elements we need to check
var $ignoreFields = $();
//get all of the fields this one can be ignored on
for(var i = 0; i < ignoreOn.length; i++) {
$ignoreFields = $ignoreFields.add(form.find('input[name="'+ignoreOn[i]+'"], select[name="'+ignoreOn[i]+'"]'));
}
//(recursively) check if any of the fields in the ignoreValidation have a value set
for(var i = 0; i < $ignoreFields.length; i++) {
if($ignoreFields.val()) {
return true;
}
return ignoreField($ignoreFields.eq(i), form);
}
}
return false;
}
[/sourcecode]
Of course we do have an issue here where an inexperienced developer could put in a circular reference and we would end up with and infinite loop, but I leave it to you to either fix that issue, or just be smart enough not to do that.
Hi, Neat post. There’s an issue together with your website in internet explorer, might test this… IE nonetheless is the marketplace chief and a huge part of other folks will pass over your wonderful writing because of this problem.
I’ll be honest, I don’t care if my site does not work in IE. My target audience is not people who would use IE.