0

I'm using the jQuery Validation library to validate forms on on my site before submitting them. I'd like to use one validate() function for all my forms which works great with just adding the required attribute to form inputs. But I've run into a snag.

I want to use validation methods from the additional-methods.js library to validate phone numbers and other special inputs. In my validate() function I would just add the following.

$('form').validate({
    rules: {
        user_phone: {
           phoneUS: true,
        },
    },
});

But that only works on inputs with the name='user_phone'. I have forms with more than one phone input. Is there a way to use the phoneUS validation method on all inputs with type='tel'?

Thanks in advance to anyone who offers any insight on this.

Edit

I'm looking for something like this...

$.validator.setDefaults({ 
   rules: {
      'type=tel': {
         phoneUS: true,
      },
   },    
});

1 Answer 1

1

No, you cannot declare rules within .validate() or .setDefaults() by anything other than one name at a time.

Is there a way to use the phoneUS validation method on all inputs with type='tel'?

Yes, with the .rules('add') method, you can use any jQuery selector and target multiple input elements at once.

$('input[type="tel"]').each(function() {
    $(this).rules('add', {
        phoneUS: true,
        // other rules
    });
});
  • You must still have a unique name on each input element.

  • You must use a jQuery .each() when the selector contains multiple elements.

  • You must still use the .validate() method to initialize the plugin on your form.

DEMO: http://jsfiddle.net/fqss7uy3/

Sign up to request clarification or add additional context in comments.

1 Comment

Ahhh that's perfect. Thanks Sparky!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.