The various ways to declare your jQuery Validate rules

The following are all acceptable methods for declaring validation rules for the jQuery Validation plugin.

1) Declared within `.validate()`

Use this when you’re trying to keep your JavaScript separate from your HTML markup.

$(document).ready(function() {
        
    $('#myform').validate({
        rules: {
            fieldName: {
                required: true
            }
        }
    });
        
});

DEMO: http://jsfiddle.net/uTt2X/2/

NOTE: If your field `name` contains special characters such as brackets or dots, you must enclose the `name` in quotes

$(document).ready(function() {
        
    $('#myform').validate({
        rules: {
            "field.Name[234]": {
                required: true
            }
        }
    });
        
});

—–

2) Declared by `class`:

Only use this when your rules can be declared by a boolean `true` as you cannot pass any parameters.

<input name="fieldName" class="required" />

DEMO: http://jsfiddle.net/uTt2X/1/

—–

3) Declared by HTML5 validation attributes:

Use this if you already have HTML 5 validation attributes within your form. Only use this when your rules can be declared with HTML 5 validation attributes. Not all rules can be declared in this fashion.

<input name="fieldName" required="required" />

DEMO: http://jsfiddle.net/uTt2X/

—–

4) Declared using the `.rules()` method:

You must use this method if you’re dynamically creating form elements.

$('input[name="fieldName"]').rules('add', {
    required: true
});

DEMO: http://jsfiddle.net/uTt2X/3/

However, as per the documentation, this method only applies to the first matched element. The solution is then to wrap it within a jQuery `.each()` for assigning rules to many inputs at once.

$('.myclass').each(function() {
    $(this).rules('add', {
        required: true
    });
});

DEMO: http://jsfiddle.net/uTt2X/8/

—–

5) By assigning one or more rules to your own `class` using the `.addClassRules()` method:

Use this for assigning rules to fields by their class or for creating an arbitrary `class` representing the rule. Great for creating “compound” rules. Compound rules are rules that are composed of two or more standard rules, like `required` and `email`.

$.validator.addClassRules("myClass", {
    required: true,
    email: true 
});

Then apply to your HTML:

<input name="fieldName" class="myClass" />

DEMO: http://jsfiddle.net/uTt2X/4/

One Reply to “The various ways to declare your jQuery Validate rules”

Leave a Reply

Your email address will not be published. Required fields are marked *