Author Archives: jzaefferer

require_from_group method

Returns: Boolean

Description: Ensures a given number of fields in a group are complete.

    Example:

    Within a group of three phone numbers, ensure at least one is complete.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    <!doctype html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>Within a group of three phone numbers, ensure at least one is complete.</title>
    <link rel="stylesheet" href="http://jqueryvalidation.org/files/demo/site-demos.css">
    </head>
    <body>
    <form id="myform">
    <label for="mobile_phone">Mobile phone: </label>
    <input class="left phone-group" id="mobile_phone" name="mobile_phone">
    <br/>
    <label for="home_phone">Home phone: </label>
    <input class="left phone-group" id="home_phone" name="home_phone">
    <br/>
    <label for="work_phone">Work phone: </label>
    <input class="left phone-group" id="Work_phone" name="work_phone">
    <br/>
    <input type="submit" value="Validate!">
    </form>
    <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
    <script src="http://jqueryvalidation.org/files/dist/jquery.validate.min.js"></script>
    <script src="http://jqueryvalidation.org/files/dist/additional-methods.min.js"></script>
    <script>
    // just for the demos, avoids form submit
    jQuery.validator.setDefaults({
    debug: true,
    success: "valid"
    });
    $( "#myform" ).validate({
    rules: {
    mobile_phone: {
    require_from_group: [1, ".phone-group"]
    },
    home_phone: {
    require_from_group: [1, ".phone-group"]
    },
    work_phone: {
    require_from_group: [1, ".phone-group"]
    }
    }
    });
    </script>
    </body>
    </html>

    Demo:

    jQuery.validator.addClassRules()

    jQuery.validator.addClassRules( name, rules )

    Description: Add a compound class method – useful to refactor common combinations of rules into a single class.

    Examples:

    Example: Add a new compound rule called “name”, replacing class=”required” minlength=”2″ with class=”name”.

    1
    2
    3
    4
    jQuery.validator.addClassRules("name", {
    required: true,
    minlength: 2
    });

    Example: Add two compound class rules for name and zip.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    jQuery.validator.addClassRules({
    name: {
    required: true,
    minlength: 2
    },
    zip: {
    required: true,
    digits: true,
    minlength: 5,
    maxlength: 5
    }
    });

    .validate()

    validate( [options ] )Returns: Validator

    Description: Validates the selected form.

    • validate( [options ] )

      • options
        Type: Object
        • debug (default: false)
          Type: Boolean
          Enables debug mode. If true, the form is not submitted and certain errors are displayed on the console (will check if a window.console property exists). Try to enable when a form is just submitted instead of validation stopping the submit.

          Example: Prevents the form from submitting and tries to help setting up the validation with warnings about missing methods and other debug messages.

          1
          2
          3
          $(".selector").validate({
          debug: true
          });
        • submitHandler (default: native form submit)
          Type: Function()
          Callback for handling the actual submit when the form is valid. Gets the form as the only argument. Replaces the default submit. The right place to submit a form via Ajax after it is validated.

          Example: Submits the form via Ajax when valid.

          1
          2
          3
          4
          5
          $(".selector").validate({
          submitHandler: function(form) {
          $(form).ajaxSubmit();
          }
          });

          Example: Use submitHandler to process something and then using the default submit. Note that “form” refers to a DOM element, this way the validation isn’t triggered again.

          1
          2
          3
          4
          5
          6
          $(".selector").validate({
          submitHandler: function(form) {
          // do other things for a valid form
          form.submit();
          }
          });

          The callback gets passed one argument:

          • form
            Type: Element
            The form currently being validated, as a DOMElement.
        • invalidHandler
          Type: Function()
          Callback for custom code when an invalid form is submitted. Called with an event object as the first argument, and the validator as the second.

          Example: Displays a message above the form, indicating how many fields are invalid when the user tries to submit an invalid form.

          1
          2
          3
          4
          5
          6
          7
          8
          9
          10
          11
          12
          13
          14
          15
          $(".selector").validate({
          invalidHandler: function(event, validator) {
          // 'this' refers to the form
          var errors = validator.numberOfInvalids();
          if (errors) {
          var message = errors == 1
          ? 'You missed 1 field. It has been highlighted'
          : 'You missed ' + errors + ' fields. They have been highlighted';
          $("div.error span").html(message);
          $("div.error").show();
          } else {
          $("div.error").hide();
          }
          }
          });

          The callback gets passed two arguments:

          • event
            Type: Event
            A custom event object, since this function is bound as an event handler.
          • validator
            Type: Validator
            The validator instance for the current form.
        • ignore (default: ":hidden")
          Type: Selector
          Elements to ignore when validating, simply filtering them out. jQuery’s not-method is used, therefore everything that is accepted by not() can be passed as this option. Inputs of type submit and reset are always ignored, so are disabled elements.

          Example: Ignores all elements with the class “ignore” when validating.

          1
          2
          3
          $("#myform").validate({
          ignore: ".ignore"
          });
        • rules (default: rules are read from markup (classes, attributes, data))
          Type: Object
          Key/value pairs defining custom rules. Key is the name of an element (or a group of checkboxes/radio buttons), value is an object consisting of rule/parameter pairs or a plain String. Can be combined with class/attribute/data rules. Each rule can be specified as having a depends-property to apply the rule only in certain conditions. See the second example below for details.

          Example: Specifies a name element as required and an email element as required (using the shortcut for a single rule) and a valid email address (using another object literal).

          1
          2
          3
          4
          5
          6
          7
          8
          9
          10
          11
          $(".selector").validate({
          rules: {
          // simple rule, converted to {required:true}
          name: "required",
          // compound rule
          email: {
          required: true,
          email: true
          }
          }
          });

          Example: Specifies a contact element as required and as email address, the latter depending on a checkbox being checked for contact via email.

          1
          2
          3
          4
          5
          6
          7
          8
          9
          10
          11
          12
          $(".selector").validate({
          rules: {
          contact: {
          required: true,
          email: {
          depends: function(element) {
          return $("#contactform_email:checked")
          }
          }
          }
          }
          });
        • messages (default: the default message for the method used)
          Type: Object
          Key/value pairs defining custom messages. Key is the name of an element, value the message to display for that element. Instead of a plain message, another map with specific messages for each rule can be used. Overrides the title attribute of an element or the default message for the method (in that order). Each message can be a String or a Callback. The callback is called in the scope of the validator, with the rule’s parameters as the first argument and the element as the second, and must return a String to display as the message.

          Example: Specifies a name element as required and an email element as required and a valid email address. A single message is specified for the name element, and two messages for email.

          1
          2
          3
          4
          5
          6
          7
          8
          9
          10
          11
          12
          13
          14
          15
          16
          $(".selector").validate({
          rules: {
          name: "required",
          email: {
          required: true,
          email: true
          }
          },
          messages: {
          name: "Please specify your name",
          email: {
          required: "We need your email address to contact you",
          email: "Your email address must be in the format of name@domain.com"
          }
          }
          });

          Example: Validates the name-field as required and having at least two characters. Provides a callback message using jQuery.format to avoid having to specify the parameter in two places.

          1
          2
          3
          4
          5
          6
          7
          8
          9
          10
          11
          12
          13
          14
          $(".selector").validate({
          rules: {
          name: {
          required: true,
          minlength: 2
          }
          },
          messages: {
          name: {
          required: "We need your email address to contact you",
          minlength: jQuery.format("At least {0} characters required!")
          }
          }
          });
        • groups
          Type: Object
          Specify grouping of error messages. A group consists of an arbitrary group name as the key and a space separated list of element names as the value. Use errorPlacement to control where the group message is placed.

          Example: Use a table layout for the form, placing error messags in the next cell after the input.

          1
          2
          3
          4
          5
          6
          7
          8
          9
          10
          11
          12
          $("#myform").validate({
          groups: {
          username: "fname lname"
          },
          errorPlacement: function(error, element) {
          if (element.attr("name") == "fname" || element.attr("name") == "lname" ) {
          error.insertAfter("#lastname");
          } else {
          error.insertAfter(element);
          }
          }
          });
        • onsubmit (default: true)
          Type: Boolean
          Validate the form on submit. Set to false to use only other events for validation.

          Set to a Function to decide for yourself when to run validation.

          A boolean true is not a valid value.

          Example: Disables onsubmit validation, allowing the user to submit whatever he wants, while still validating on keyup/blur/click events (if not specified otherwise).

          1
          2
          3
          $(".selector").validate({
          onsubmit: false
          });
        • onfocusout
          Type: Boolean or Function()
          Validate elements (except checkboxes/radio buttons) on blur. If nothing is entered, all rules are skipped, except when the field was already marked as invalid.

          Set to a Function to decide for yourself when to run validation.

          A boolean true is not a valid value.

          Example: Disables onblur validation.

          1
          2
          3
          $(".selector").validate({
          onfocusout: false
          });

          The callback gets passed two arguments:

          • element
            Type: Element
            The element currently being validated, as a DOMElement.
          • event
            Type: Event
            The event object for this focusout event.
        • onkeyup
          Type: Boolean or Function()
          Validate elements on keyup. As long as the field is not marked as invalid, nothing happens. Otherwise, all rules are checked on each key up event. Set to false to disable.

          Set to a Function to decide for yourself when to run validation.

          A boolean true is not a valid value.

          Example: Disables onkeyup validation.

          1
          2
          3
          $(".selector").validate({
          onkeyup: false
          });

          The callback gets passed two arguments:

          • element
            Type: Element
            The element currently being validated, as a DOMElement.
          • event
            Type: Event
            The event object for this keyup event.
        • onclick
          Type: Boolean or Function()
          Validate checkboxes and radio buttons on click. Set to false to disable.

          Set to a Function to decide for yourself when to run validation.

          A boolean true is not a valid value.

          Example: Disables onclick validation of checkboxes and radio buttons.

          1
          2
          3
          $(".selector").validate({
          onclick: false
          });

          The callback gets passed two arguments:

          • element
            Type: Element
            The element currently being validated, as a DOMElement.
          • event
            Type: Event
            The event object for this click event.
        • focusInvalid (default: true)
          Type: Boolean
          Focus the last active or first invalid element on submit via validator.focusInvalid(). The last active element is the one that had focus when the form was submitted, avoiding stealing its focus. If there was no element focused, the first one in the form gets it, unless this option is turned off.

          Example: Disables focusing of invalid elements.

          1
          2
          3
          $(".selector").validate({
          focusInvalid: false
          });
        • focusCleanup (default: false)
          Type: Boolean
          If enabled, removes the errorClass from the invalid elements and hides all error messages whenever the element is focused. Avoid combination with focusInvalid.

          Example: Enables cleanup when focusing elements, removing the error class and hiding error messages when an element is focused.

          1
          2
          3
          $(".selector").validate({
          focusCleanup: true
          });
        • errorClass (default: "error")
          Type: String
          Use this class to create error labels, to look for existing error labels and to add it to invalid elements.

          Example: Sets the error class to “invalid”.

          1
          2
          3
          $(".selector").validate({
          errorClass: "invalid"
          });
        • validClass (default: "valid")
          Type: String
          This class is added to an element after it was validated and considered valid.

          Example: Sets the valid class to “success”.

          1
          2
          3
          $(".selector").validate({
          validClass: "success"
          });
        • errorElement (default: "label")
          Type: String
          Use this element type to create error messages and to look for existing error messages. The default, “label”, has the advantage of creating a meaningful link between error message and invalid field using the for attribute (which is always used, regardless of element type).

          Example: Sets the error element to “em”.

          1
          2
          3
          $(".selector").validate({
          errorElement: "em"
          });
        • wrapper (default: window)
          Type: String
          Wrap error labels with the specified element. Useful in combination with errorLabelContainer to create a list of error messages.

          Example: Wrap each error element with a list item, useful when using an ordered or unordered list as the error container.

          1
          2
          3
          $(".selector").validate({
          wrapper: "li"
          });
        • errorLabelContainer
          Type: Selector
          Hide and show this container when validating.

          Example: All error labels are displayed inside an unordered list with the ID “messageBox”, as specified by the selector passed as errorContainer option. All error elements are wrapped inside a li element, to create a list of messages.

          1
          2
          3
          4
          5
          $("#myform").validate({
          errorLabelContainer: "#messageBox",
          wrapper: "li",
          submitHandler: function() { alert("Submitted!") }
          });
        • errorContainer
          Type: Selector
          Hide and show this container when validating.

          Example: Uses an additonal container for error messages. The elements given as the errorContainer are all shown and hidden when errors occur. However, the error labels themselves are added to the element(s) given as errorLabelContainer, here an unordered list. Therefore the error labels are also wrapped into li elements (wrapper option).

          1
          2
          3
          4
          5
          6
          $("#myform").validate({
          errorContainer: "#messageBox1, #messageBox2",
          errorLabelContainer: "#messageBox1 ul",
          wrapper: "li", debug:true,
          submitHandler: function() { alert("Submitted!") }
          });
        • showErrors
          Type: Function()
          A custom message display handler. Gets the map of errors as the first argument and an array of errors as the second, called in the context of the validator object. The arguments contain only those elements currently validated, which can be a single element when doing validation onblur/keyup. You can trigger (in addition to your own messages) the default behaviour by calling this.defaultShowErrors().

          Example: Update the number of invalid elements each time an error is displayed. Delegates to the default implementation for the actual error display.

          1
          2
          3
          4
          5
          6
          7
          8
          $(".selector").validate({
          showErrors: function(errorMap, errorList) {
          $("#summary").html("Your form contains "
          + this.numberOfInvalids()
          + " errors, see details below.");
          this.defaultShowErrors();
          }
          });

          The callback gets passed two arguments:

          • errorMap
            Type: Object
            Key/value pairs, where the key refers to the name of an input field, values the message to be displayed for that input.
          • errorList
            Type: Array
            An array for all currently validated elements. Contains objects with the following two properties:
            • message
              Type: String
              The message to be displayed for an input.
            • element
              Type: Element
              The DOMElement for this entry.
        • errorPlacement (default: Places the error label after the invalid element)
          Type: Function()
          Customize placement of created error labels. First argument: The created error label as a jQuery object. Second argument: The invalid element as a jQuery object.

          Example: Use a table layout for the form, placing error messages in the next cell after the input.

          1
          2
          3
          4
          5
          $("#myform").validate({
          errorPlacement: function(error, element) {
          error.appendTo( element.parent("td").next("td") );
          }
          });

          The callback gets passed two arguments:

          • error
            Type: jQuery
            The error label to insert into the DOM.
          • element
            Type: jQuery
            The validated input, for relative positioning.
        • success
          Type: String or Function()
          If specified, the error label is displayed to show a valid element. If a String is given, it is added as a class to the label. If a Function is given, it is called with the label (as a jQuery object) and the validated input (as a DOM element). The label can be used to add a text like “ok!”.

          Example: Add a class “valid” to valid elements, styled via CSS.

          1
          2
          3
          4
          $("#myform").validate({
          success: "valid",
          submitHandler: function() { alert("Submitted!") }
          });

          Example: Add a class “valid” to valid elements, styled via CSS, and add the text “Ok!”.

          1
          2
          3
          4
          5
          6
          $("#myform").validate({
          success: function(label) {
          label.addClass("valid").text("Ok!")
          },
          submitHandler: function() { alert("Submitted!") }
          });

          The callback gets passed two arguments:

          • label
            Type: jQuery
            The error label. Use to add a class or replace the text content.
          • element
            Type: Element
            The element currently being validated, as a DOMElement.
        • highlight (default: Adds errorClass (see the option) to the element)
          Type: Function()
          How to highlight invalid fields. Override to decide which fields and how to highlight.

          Example: Highlights an invalid element by fading it out and in again.

          1
          2
          3
          4
          5
          6
          7
          $(".selector").validate({
          highlight: function(element, errorClass) {
          $(element).fadeOut(function() {
          $(element).fadeIn();
          });
          }
          });

          Example: Adds the error class to both the invalid element and its label

          1
          2
          3
          4
          5
          6
          7
          8
          9
          10
          11
          12
          $(".selector").validate({
          highlight: function(element, errorClass, validClass) {
          $(element).addClass(errorClass).removeClass(validClass);
          $(element.form).find("label[for=" + element.id + "]")
          .addClass(errorClass);
          },
          unhighlight: function(element, errorClass, validClass) {
          $(element).removeClass(errorClass).addClass(validClass);
          $(element.form).find("label[for=" + element.id + "]")
          .removeClass(errorClass);
          }
          });

          The callback gets passed three arguments:

          • element
            Type: Element
            The invalid DOM element, usually an input.
          • errorClass
            Type: String
            Current value of the errorClass option.
          • validClass
            Type: String
            Current value of the validClass option.
        • unhighlight (default: Removes the errorClass)
          Type: Function()
          Called to revert changes made by option highlight, same arguments as highlight.
        • ignoreTitle (default: false)
          Type: Boolean
          Set to skip reading messages from the title attribute, helps to avoid issues with Google Toolbar; default is false for compability, the message-from-title is likely to be completely removed in a future release.

          Example: Configure the plugin to ignore title attributes on validated elements when looking for messages.

          1
          2
          3
          $(".selector").validate({
          ignoreTitle: true
          });
    This method sets up event handlers for submit, focus, keyup, blur and click to trigger validation of the entire form or individual elements. Each one can be disabled, see the onxxx options (onsubmit, onfocusout, onkeyup, onclick). focusInvalid focuses elements when submitting an invalid form.

    Use the debug option to ease setting up validation rules, it always prevents the default submit, even when script errors occur.

    Use submitHandler to implement your own form submit, eg. via Ajax. Use invalidHandler to react when an invalid form is submitted.

    Use rules and messages to specify which elements to validate, and how. See rules() for more details about specifying validation rules.

    Use errorClass, errorElement, wrapper, errorLabelContainer, errorContainer, showErrors, success, errorPlacement, highlight, unhighlight, and ignoreTitle to control how invalid elements and error messages are displayed.

    .valid()

    valid()Returns: Boolean

    Description: Checks whether the selected form is valid or whether all selected elements are valid.

    • valid()

      • This method does not accept any arguments.
    validate() needs to be called on the form before checking it using this method.

    Example:

    Sets up validation for a form, then checks if the form is valid when clicking a button.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    <!doctype html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>Sets up validation for a form, then checks if the form is valid when clicking a button.</title>
    <link rel="stylesheet" href="http://jqueryvalidation.org/files/demo/site-demos.css">
    <style>
    </style>
    </head>
    <body>
    <form id="myform">
    <form id="myform">
    <input type="text" name="name" required>
    <br>
    <button type="button">Validate!</button>
    </form>
    </form>
    <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
    <script src="http://jqueryvalidation.org/files/dist/jquery.validate.min.js"></script>
    <script src="http://jqueryvalidation.org/files/dist/additional-methods.min.js"></script>
    <script>
    // just for the demos, avoids form submit
    jQuery.validator.setDefaults({
    debug: true,
    success: "valid"
    });
    var form = $( "#myform" );
    form.validate();
    $( "button" ).click(function() {
    alert( "Valid: " + form.valid() );
    });
    </script>
    </body>
    </html>

    Demo:

    url method

    Returns: Boolean

    Description: Makes the element require a valid url

      Return true, if the value is a valid url.

      Works with text inputs.

      Example:

      Makes “field” required and a url.

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      33
      34
      35
      <!doctype html>
      <html>
      <head>
      <meta charset="utf-8">
      <title>Makes "field" required and a url.</title>
      <link rel="stylesheet" href="http://jqueryvalidation.org/files/demo/site-demos.css">
      </head>
      <body>
      <form id="myform">
      <label for="field">Required, URL: </label>
      <input class="left" id="field" name="field">
      <br/>
      <input type="submit" value="Validate!">
      </form>
      <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
      <script src="http://jqueryvalidation.org/files/dist/jquery.validate.min.js"></script>
      <script src="http://jqueryvalidation.org/files/dist/additional-methods.min.js"></script>
      <script>
      // just for the demos, avoids form submit
      jQuery.validator.setDefaults({
      debug: true,
      success: "valid"
      });
      $( "#myform" ).validate({
      rules: {
      field: {
      required: true,
      url: true
      }
      }
      });
      </script>
      </body>
      </html>

      Demo:

      :unchecked Selector

      unchecked selector

      Description: Selects all elements that are unchecked.

      • jQuery( “:unchecked” )

      Inversion of :checked.

      Example:

      Finds all input elements that are unchecked.

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      33
      34
      35
      36
      37
      38
      39
      40
      41
      <!doctype html>
      <html>
      <head>
      <meta charset="utf-8">
      <title>Finds all input elements that are unchecked.</title>
      <link rel="stylesheet" href="http://jqueryvalidation.org/files/demo/site-demos.css">
      <style>
      div { color:red; }
      </style>
      </head>
      <body>
      <form id="myform">
      <form>
      <input type="checkbox" name="newsletter" checked="checked" value="Hourly" />
      <input type="checkbox" name="newsletter" value="Daily" />
      <input type="checkbox" name="newsletter" value="Weekly" />
      <input type="checkbox" name="newsletter" checked="checked" value="Monthly" />
      <input type="checkbox" name="newsletter" value="Yearly" />
      </form>
      <div></div>
      </form>
      <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
      <script src="http://jqueryvalidation.org/files/dist/jquery.validate.min.js"></script>
      <script src="http://jqueryvalidation.org/files/dist/additional-methods.min.js"></script>
      <script>
      // just for the demos, avoids form submit
      jQuery.validator.setDefaults({
      debug: true,
      success: "valid"
      });
      function countUnchecked() {
      var n = $( "input:unchecked" ).length;
      $( "div" ).text(n + (n == 1 ? " is" : " are") + " unchecked!" );
      }
      countUnchecked();
      $( ":checkbox" ).click( countUnchecked );
      </script>
      </body>
      </html>

      Demo:

      .rules()

      rules()Returns: Object

      Description: Read, add and remove rules for an element.

      • rules()

        • This method does not accept any arguments.
      • rules( “add”, rules )

        • “add”
          Type: String
        • rules
          Type: Object
          The rules to add. Accepts the same format as the rules-option of the validate-method.
      • rules( “remove”, rules )

        • “remove”
          Type: String
        • rules
          Type: Object
          The space-seperated names of rules to remove and return. If left unspecified, removes and returns all rules. Manipulates only rules specified via rules-option or via rules(“add”).
      Returns the validations rules for the first selected element or

      Adds the specified rules and returns all rules for the first matched element. Requires that the parent form is validated, that is, $( “form” ).validate() is called first or

      Removes the specified rules and returns all rules for the first matched element.

      There are several ways to specify validation rules.

      • Validation methods without parameters can be specified as classes on the element (recommended)
      • Validation methods with parameters can be specified as attributes (recommended)
      • Both can be specified as metadata using the metadata plugin
      • Both can be specified using the rules-option of the validate()-method

      When setting, the rules can also contain a messages-object, specifying custom messages for existing or added rules.

      Examples:

      Example: Adds minlength: 2 to an element which is already required.

      1
      2
      3
      $( "#myinput" ).rules( "add", {
      minlength: 2
      });

      Example: Adds required and minlength: 2 to an element and specifies custom messages for both.

      1
      2
      3
      4
      5
      6
      7
      8
      $( "#myinput" ).rules( "add", {
      required: true,
      minlength: 2,
      messages: {
      required: "Required input",
      minlength: jQuery.format("Please, at least {0} characters are necessary")
      }
      });

      Example: Removes all static rules from an element.

      1
      $( "#myinput" ).rules( "remove" );

      Example: Removes min and max rules from an element.

      1
      $( "#myinput" ).rules( "remove", "min max" );

      required method

      required()Returns: Boolean

      Description: Makes the element required.

      • required()

        • This method does not accept any arguments.
      • required( dependency-expression )

        • dependency-expression
          Type: String
          An expression (String) that is evaluated in the context of the element’s form, making the field required only if the expression returns more than one element.

          Very often your expression will use selector filters such as #foo:checked, #foo:filled, #foo:visible. This plugin provides custom selectors for that purpose.

      • required( dependency-callback )

        • dependency-callback
          Type: Function()
          The function is executed with the element as it’s only argument: If it returns true, the element is required.
      Return false, if the element is empty (text input) or unchecked (radio/checkbox) or if nothing is selected (select).

      Works with text inputs, selects, checkboxes and radio buttons.

      To force a user to select an option from a select box, provide an empty option element like <option value=””>Choose…</option>

      Examples:

      Example: Makes “field” always required. Nothing and blanks are invalid.

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      33
      34
      <!doctype html>
      <html>
      <head>
      <meta charset="utf-8">
      <title>Makes "field" always required. Nothing and blanks are invalid.</title>
      <link rel="stylesheet" href="http://jqueryvalidation.org/files/demo/site-demos.css">
      </head>
      <body>
      <form id="myform">
      <label for="field">Required: </label>
      <input type="text" class="left" id="field" name="field">
      <br/>
      <input type="submit" value="Validate!">
      </form>
      <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
      <script src="http://jqueryvalidation.org/files/dist/jquery.validate.min.js"></script>
      <script src="http://jqueryvalidation.org/files/dist/additional-methods.min.js"></script>
      <script>
      // just for the demos, avoids form submit
      jQuery.validator.setDefaults({
      debug: true,
      success: "valid"
      });
      $( "#myform" ).validate({
      rules: {
      field: {
      required: true
      }
      }
      });
      </script>
      </body>
      </html>

      Demo:

      Example: Makes the fruit select required.

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      33
      34
      35
      36
      37
      38
      39
      <!doctype html>
      <html>
      <head>
      <meta charset="utf-8">
      <title>Makes the fruit select required.</title>
      <link rel="stylesheet" href="http://jqueryvalidation.org/files/demo/site-demos.css">
      </head>
      <body>
      <form id="myform">
      <label for="fruit">Please select a fruit</label>
      <select id="fruit" name="fruit" title="Please select something!">
      <option value="">Select...</option>
      <option value="1">Banana</option>
      <option value="2">Apple</option>
      <option value="3">Peach</option>
      </select>
      <br/>
      <input type="submit" value="Validate!">
      </form>
      <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
      <script src="http://jqueryvalidation.org/files/dist/jquery.validate.min.js"></script>
      <script src="http://jqueryvalidation.org/files/dist/additional-methods.min.js"></script>
      <script>
      // just for the demos, avoids form submit
      jQuery.validator.setDefaults({
      debug: true,
      success: "valid"
      });
      $( "#myform" ).validate({
      rules: {
      fruit: {
      required: true
      }
      }
      });
      </script>
      </body>
      </html>

      Demo:

      Example: Makes the gender radio buttons required.

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      33
      34
      35
      36
      37
      38
      39
      40
      41
      <!doctype html>
      <html>
      <head>
      <meta charset="utf-8">
      <title>Makes the gender radio buttons required.</title>
      <link rel="stylesheet" href="http://jqueryvalidation.org/files/demo/site-demos.css">
      </head>
      <body>
      <form id="myform">
      <label for="gender_male">
      <input type="radio" id="gender_male" value="m" name="gender" />
      Male
      </label>
      <label for="gender_female">
      <input type="radio" id="gender_female" value="f" name="gender"/>
      Female
      </label>
      <label for="gender" class="error">Please select your gender</label>
      <br/>
      <input type="submit" value="Validate!">
      </form>
      <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
      <script src="http://jqueryvalidation.org/files/dist/jquery.validate.min.js"></script>
      <script src="http://jqueryvalidation.org/files/dist/additional-methods.min.js"></script>
      <script>
      // just for the demos, avoids form submit
      jQuery.validator.setDefaults({
      debug: true,
      success: "valid"
      });
      $( "#myform" ).validate({
      rules: {
      gender: {
      required: true
      }
      }
      });
      </script>
      </body>
      </html>

      Demo:

      Example: Makes the agree checkbox required.

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      33
      34
      <!doctype html>
      <html>
      <head>
      <meta charset="utf-8">
      <title>Makes the agree checkbox required.</title>
      <link rel="stylesheet" href="http://jqueryvalidation.org/files/demo/site-demos.css">
      </head>
      <body>
      <form id="myform">
      <label for="agree">Please agree to our policy</label>
      <input type="checkbox" id="agree" title="Please agree to our policy!" name="agree" />
      <br/>
      <input type="submit" value="Validate!">
      </form>
      <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
      <script src="http://jqueryvalidation.org/files/dist/jquery.validate.min.js"></script>
      <script src="http://jqueryvalidation.org/files/dist/additional-methods.min.js"></script>
      <script>
      // just for the demos, avoids form submit
      jQuery.validator.setDefaults({
      debug: true,
      success: "valid"
      });
      $( "#myform" ).validate({
      rules: {
      agree: {
      required: true
      }
      }
      });
      </script>
      </body>
      </html>

      Demo:

      Example: Makes details required only if #other is checked.

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      33
      34
      35
      36
      <!doctype html>
      <html>
      <head>
      <meta charset="utf-8">
      <title>Makes details required only if #other is checked.</title>
      <link rel="stylesheet" href="http://jqueryvalidation.org/files/demo/site-demos.css">
      </head>
      <body>
      <form id="myform">
      <label for="other">Check to make next field required</label>
      <input id="other" type="checkbox">
      <br>
      <input id="details" name="details">
      <br>
      <input type="submit" value="Validate!">
      </form>
      <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
      <script src="http://jqueryvalidation.org/files/dist/jquery.validate.min.js"></script>
      <script src="http://jqueryvalidation.org/files/dist/additional-methods.min.js"></script>
      <script>
      // just for the demos, avoids form submit
      jQuery.validator.setDefaults({
      debug: true,
      success: "valid"
      });
      $( "#myform" ).validate({
      rules: {
      details: {
      required: "#other:checked"
      }
      }
      });
      </script>
      </body>
      </html>

      Demo:

      Example: Makes “parent” required only if age is below 13.

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      33
      34
      35
      36
      37
      38
      39
      40
      41
      42
      43
      <!doctype html>
      <html>
      <head>
      <meta charset="utf-8">
      <title>Makes "parent" required only if age is below 13.</title>
      <link rel="stylesheet" href="http://jqueryvalidation.org/files/demo/site-demos.css">
      </head>
      <body>
      <form id="myform">
      <label>Age </label>
      <input id="age" name="age">
      <br>
      <label>Parent </label>
      <input id="parent" name="parent">
      <br>
      <input type="submit" value="Validate!">
      </form>
      <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
      <script src="http://jqueryvalidation.org/files/dist/jquery.validate.min.js"></script>
      <script src="http://jqueryvalidation.org/files/dist/additional-methods.min.js"></script>
      <script>
      // just for the demos, avoids form submit
      jQuery.validator.setDefaults({
      debug: true,
      success: "valid"
      });
      $( "#myform" ).validate({
      rules: {
      age: {
      required: true,
      min: 3
      },
      parent: {
      required: function(element) {
      return $("#age").val() < 13;
      }
      }
      }
      });
      </script>
      </body>
      </html>

      Demo:

      remote method

      remote( options )Returns: Boolean

      Description: Requests a resource to check the element for validity.

      • remote( options )

        • options
          Type: Object
          For the URL of the resource to request for serverside validation (String) or options to fully customize the request, see jQuery.ajax for details.

          These options deep-extend the defaults (dataType:"json", data:{nameOfTheElement:valueOfTheElement}). Any options you provide will override the defaults.

      The serverside resource is called via jQuery.ajax (XMLHttpRequest) and gets a key/value pair corresponding to the name of the validated element and its value as a GET parameter. The response is evaluated as JSON and must be true for valid elements, and can be any false, undefined or null for invalid elements, using the default message; or a string, eg. "That name is already taken, try peter123 instead" to display as the error message.

      For more examples, take a look the marketo demo and the milk demo.

      Examples:

      Example: Makes the email field required, an email and does a remote request to check if the given address is already taken.

      1
      2
      3
      4
      5
      6
      7
      8
      9
      $( "#myform" ).validate({
      rules: {
      email: {
      required: true,
      email: true,
      remote: "check-email.php"
      }
      }
      });

      Example: Makes the email field required, an email and does a remote request to check if the given address is already taken. In addition, the http method is set to “post” and the username is sent alongside the email address.

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      $( "#myform" ).validate({
      rules: {
      email: {
      required: true,
      email: true,
      remote: {
      url: "check-email.php",
      type: "post",
      data: {
      username: function() {
      return $( "#username" ).val();
      }
      }
      }
      }
      }
      });

      rangelength method

      rangelength( range )Returns: Boolean

      Description: Makes the element require a given value range.

      Return false if the element is

      • some kind of text input and its length is too short or too long
      • a set of checkboxes that doesn’t have enough, or has too many boxes checked
      • a select that doesn’t have enough, or has too many options selected

      Works with text inputs, selects and checkboxes.

      Example:

      Makes “field” required and between 2 and 6 characters long.

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      33
      34
      35
      <!doctype html>
      <html>
      <head>
      <meta charset="utf-8">
      <title>Makes "field" required and between 2 and 6 characters long.</title>
      <link rel="stylesheet" href="http://jqueryvalidation.org/files/demo/site-demos.css">
      </head>
      <body>
      <form id="myform">
      <label for="field">Required, minium length 2, maximum length 6: </label>
      <input type="text" class="left" id="field" name="field">
      <br/>
      <input type="submit" value="Validate!">
      </form>
      <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
      <script src="http://jqueryvalidation.org/files/dist/jquery.validate.min.js"></script>
      <script src="http://jqueryvalidation.org/files/dist/additional-methods.min.js"></script>
      <script>
      // just for the demos, avoids form submit
      jQuery.validator.setDefaults({
      debug: true,
      success: "valid"
      });
      $( "#myform" ).validate({
      rules: {
      field: {
      required: true,
      rangelength: [2, 6]
      }
      }
      });
      </script>
      </body>
      </html>

      Demo: