Update (from your comment below).
You aren't returning true from your custom rule if the if isn't entered, which technically results in undefined being returned to the caller (which is a falsey value). Update your rule as follows:
$.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);
}
return true;
}, "Mobile Required");
Leaving this part around because it might be useful to someone else:
I would update your validate call and rule as follows:
$.validator.addMethod("regex", function(value, element, regexp) {
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}",
required: "#receive_sms_updates:checked"
}
}
});
As you can see, the required property takes a "dependency-expression" which is used to determine whether or not the mobile field is required (based on whether or not #receive_sms_updates is 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 messages property on your validate call. Something like:
$.validator.addMethod("regex", function(value, element, regexp) {
var re = new RegExp(regexp);
return this.optional(element) || re.test(value);
});
$("form#patient-detials").validate({
rules: {
'patient[person_attributes][phone_mobile]': {
maxlength: 10,
minlength: 10,
digits: true,
regex: "^04[0-9]{8}",
required: "#receive_sms_updates:checked"
}
},
messages: {
'patient[person_attributes][phone_mobile]': {
required: "Mobile Required",
regex: "Please enter a valid mobile number"
}
}
});
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.