views:

77

answers:

1

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. =\

+1  A: 

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.

Nick Craver
Well holy crap that worked! Thank you for that. I will def dig into the additional methods you mentioned.
creativetim
@creativetim - Welcome :) and welcome to SO!, be sure to accept answers that resolve your questions via the check-mark on the left of the answer that helps:)
Nick Craver
It does! Done and done.
creativetim