Problem I want to validate a field using a custom validator I've created that's essentially a regex for a phone number only IF the field has a value, otherwise it doesn't need to be validated because it's optional.
Custom validator:
$.validator.addMethod('phone', function (value) {
return /^[01]?[- .]?\(?[2-9]\d{2}\)?[- .]?\d{3}[- .]?\d{4}$/.test(value);
}, 'Please enter a valid US phone number.');
Rules:
phone: {
required: true,
phone: true
},
fax: {
phone: true
}
I've even tried:
phone: {
required: true,
phone: true
},
fax: {
required: function(element){
if (!$("#cf-fax").val()) { return true; } else { return false; }
}
phone: true
}
For reference this is the field I'm trying to reference:
<input type="text" name="fax" class="optional" size="15" maxlength="14" id="cf-fax" />
Any help is appreciated because I am just plain lost. =\
Unobtrusive Validation means without writing a lot of validation code, you can perform simple client-side validation by adding the suitable attributes and including the suitable script files. These unobtrusive validation libraries need to be added: jquery.validate.min.js.
Your answer The "$(...). validate is not a function" jQuery error occurs when the jQuery validation plugin is not loaded or the jQuery-related scripts are loaded in an incorrect order. The validation plugin should be loaded after the jQuery library.
The jquery validate plugin requires a form element to function, so you should have your form fields (no matter how few) contained inside a form. You can tell the validation plugin not to operate on form submission, then manually validate the form when the correct submit button is clicked.
When you want it as optional field then say "checkName: optional".
You can call .optional()
(defined inside the validation plugin) like this
$.validator.addMethod('phone', function (value, element) {
return this.optional(element) || /^[01]?[- .]?\(?[2-9]\d{2}\)?[- .]?\d{3}[- .]?\d{4}$/.test(value);
}, 'Please enter a valid US phone number.');
This is the standard scheme for the validation plugin, take a look at their additional methods here for examples.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With