jQuery validator plug-in: validate optional field

10,036

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.

Share:
10,036

Related videos on Youtube

creativetim
Author by

creativetim

Started building websites in the mid-90's via my biggest passion at the time: Metallica. From Angelfire to server-side programming. Been bouncing back and forth from the back- to the front-end ever since. I currently enjoy a healthy dose of JavaScript in the form of large React and React Native applications. I've found that I prefer the web however.

Updated on May 01, 2022

Comments

  • creativetim
    creativetim about 2 years

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