Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use jquery validate "depends" on rules other than "required"?

Every example of "depends" I can find on the web uses the "required" rule. Clearly this is not sufficient. How do I use the "depends" clause with, for example, a "regex" rule?

I have two radio buttons, if one is selected, I regex-validate a textbox. If the other is selected, I don't care what is in the textbox.

like image 881
svinja Avatar asked Jun 04 '14 13:06

svinja


People also ask

Does jQuery validate require a form?

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.

How do you check if jQuery validate is working?

fn , so simply check whether it exists or not; if (typeof jQuery. fn. validationPlugin === "function") { // It's loaded } else { // It's not. }

What is jQuery validate unobtrusive?

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.


1 Answers

The 2nd example in the documentation uses email:

$(".selector").validate({
  rules: {
    contact: {
      required: true,
      email: {
        depends: function(element) {
          return $("#contactform_email:checked")
        }
      }
    }
  }
});

In summary, that rule is saying "contact is required and it must be an email address if #contactform_email checkbox is checked".

So if you wanted to do that with a regex (or any parameter-requiring rule method), it looks like this:

        minlength: {
            param:6,
            depends: function (element) {
                return $('#len').is(':checked');
            }
        }

Which says "The min length is 6 but only when the #len checkbox is checked".

See it in action here: http://jsfiddle.net/ryleyb/8Nsm3/

like image 117
Ryley Avatar answered Oct 02 '22 20:10

Ryley