I’ve got an input field for a phone number with the option for SMS updates. I want to check that when the SMS checkbox is checked that the number is a mobile number. I’ve got the regex working, and this is validating, but have got the ‘mobile require’ error showing even when then check box isn’t checked.
$.validator.addMethod(
"regex",
function(value, element, regexp) {
if($('#receive_sms_updates').is(':checked')) {
var check = false;
var re = new RegExp(regexp);
return this.optional(element) || re.test(value);
}
}, "Mobile Required"
);
$("form#patient-detials").validate({
rules: {
'patient[person_attributes][phone_mobile]': {
maxlength: 10,
minlength: 10,
digits: true,
regex: "^04[0-9]{8}"
}
}
});
Update (from your comment below).
You aren’t returning true from your custom rule if the
ifisn’t entered, which technically results inundefinedbeing returned to the caller (which is a falsey value). Update your rule as follows:Leaving this part around because it might be useful to someone else:
I would update your validate call and rule as follows:
As you can see, the
requiredproperty takes a “dependency-expression” which is used to determine whether or not the mobile field is required (based on whether or not#receive_sms_updatesis checked).Here’s an example: http://jsfiddle.net/andrewwhitaker/ED6cX/
To take it just one small step further, I would recommend removing the “Mobile Required” method from the rule itself (you want a re-usable regex rule after all), and place it on the
messagesproperty on your validate call. Something like:Example: http://jsfiddle.net/andrewwhitaker/5BVCK/
This way you aren’t restricting your validation rule (which is generic enough that it could apply to other fields) with a particular form.