Need a little help. So got a form, where I\'ve got two fields mobile and telephone. Only one is required. My code below does that, but what I would like is I don\'t want peo
From a quick read of the documentation, it looks like the validator's default methods are designed to operate on fields which have no knowledge of other fields. It might be neater to define your own:
function XOR_value_validator(value, el, args) {
var otherValue = $(args[0]).val();
return (value && !otherValue) || (!value && otherValue);
}
jQuery.validator.addMethod(
'XOR_with',
XOR_value_validator,
jQuery.validator.format('{1}')
);
And use something like:
mobile : {
XOR_with: [
'#telephone', // assumed to be a jQuery selector for an element with a value()
'Please enter either a telephone number or a mobile number.' // error message
]
},
telephone: {
XOR_with: [
'#mobile', // assumed to be a jQuery selector for an element with a value()
'Please enter either a telephone number or a mobile number.' // error message
]
}
http://jqueryvalidation.org/jQuery.validator.addMethod
This comes with no warranty! :P I wrote it completely untested (from the docs) in this text area.
Edit:
Regarding the comments:
You could probably shoehorn in functionality to enable/disable form elements accordingly, if this code is continually executed as the user fills out the form. However, I would advise against that, since this part of your code should only really be concerned with validation and not UX.
To extend the functionality for more than two fields (again, not tested) you might do:
function one_field_allowed_validator(value, el, args) {
var otherFields = args[0],
valuesFound = value ? 1 : 0;
for (var i = 0, limit = otherFields.length; i < limit; ++i) {
var val = $(otherFields[i]).val();
if (val && ++valuesFound === 2) {
return false;
}
}
return valuesFound !== 0;
}
jQuery.validator.addMethod(
'Allow_one_with',
one_field_allowed_validator,
jQuery.validator.format('{1}')
);
Usage:
mobile : {
Allow_one_with: [
['#telephone', '#work'],
'Please enter a telephone number, a mobile number or a work number.'
]
},
telephone: {
Allow_one_with: [
['#mobile', '#work'],
'Please enter a telephone number, a mobile number or a work number.'
]
},
work: {
Allow_one_with: [
['#mobile', '#telephone']
'Please enter a telephone number, a mobile number or a work number.'
]
}
It's feeling pretty hacky now! With every additional field in your Allow_one_with group, you must update all existing Allow_one_with validations (to include the new field and probably a new error message). I would be reluctant to use my method for more than the XOR.