Reputation: 8850
I have a form where the required field is depend on another form field value. So the required rule may be true or false depend on the other field. The issue is accept rule should be there if only the required is true. How can I do that?
...,
fieldA: {
maxlength: 3,
accept: "[0-9]{3}",
required: function() {
if($('#fieldB').val() == 'ABCD') {
return false;
} else {
return true;
}
}
},...
Thanks in advance.
Upvotes: 0
Views: 1251
Reputation: 8850
I didn't realize the 'accept' rule is a custom rule. I edited the code to check whether its an optional field. this.optional(element)
jQuery.validator.addMethod("accept", function(value, element, param) {
return this.optional(element) || value.match(new RegExp("^" + param + "$"));
});
@Barmar Thanks for the help.
Upvotes: 1
Reputation: 165
Unfortunately your required
function will likely only get called when the form is rendered, and won't update the dependent field as the independent one changes. You could use a dymanic ui library like react or knockout, or you could simply bind a .change() handler to the independent field that manipulates the attributes of the other.
You could also bind something to .submit() that prevents submission if the configuration is not correct.
Upvotes: 0