0

I am using the jQuery validate plugin to validate my form. As I see it (I'm having a hard time figuring things out from the documentation), I have 2 basic choices of how to apply a built-in validation rule:

  1. Apply the class in the HTML

    <input name="myNum" id="myNum" type="text" class="number" />

  2. Specify the rule by input id when calling the validate method

    $('#sales').validate({
        rules: {
            myNum: {number: true}
        }
    });
    

Which is considered "best-practice"? I'm trying to decide if it's clearer to just code all the rules in one place in the validate method, so that I can see all my validation in one centralized location, or if it makes sense to code the simple rules in the HTML as classes and only put customized validation in the validate method. What is the more accepted way of coding the validation? What should determine when I use which method?

froadie
  • 79,995
  • 75
  • 166
  • 235
  • I think this is more personal choice. I personally use the first method, as the validation relates to that input. – Vincent P Jan 17 '13 at 09:46
  • There are so many different ways to use this plugin, I don't think there's any one "best practice". It's going to depend on how many fields, how your rules are defined, etc. I created a very long and complex form and it made more sense in my case to use a combination of all methods. – Sparky Jan 17 '13 at 16:26

2 Answers2

4

The only factor other than personal choice that you need to consider is that if the method that you want applied as a rule is one that takes an additional parameter, then you cannot use the method name as a classname. For instance these methods

  • minlength,
  • maxlength
  • rangelength
  • min
  • max
  • range
  • equalTo

all take a parameter - ie their definition is

function(value, element, param)

rather than

function(value, element)

So this markup will not work

<!-- doesn't work --> 
<input name="email2" class="minlength"/>

Methods that don't take an extra parameter are 'required', 'email', 'url', 'date' etc.

So even for your own custom methods you can apply them to a form field by classname, as long as they have a signature function(value, element)

The docs are not fully up to date - there are multiple ways to apply a method to an input field in markup, including the data- attributes which are not mentioned in the documentation at all. For example these are all valid:

<input name="email1" required />
<input name="email2" class="required"/>
<input name="email3" type="required"/>
<input name="email4" data-rule-required="true" />
<input name="email5" data-rule-required="true" data-rule-minlength="5" />
<input name="email6" data-rule-required="true" data-rule-range="[1,5]"/>

nb. for the data- style you need an up to date version of the plugin

politus
  • 5,996
  • 1
  • 33
  • 42
  • should be no comma - class="required digits" – politus Jan 17 '13 at 16:34
  • I thought there was supposed to be a way to define all the rules inline (although it was undocumented). It's discussed [in this question](http://stackoverflow.com/q/13160201/594235), but it does not seem to work. – Sparky Jan 17 '13 at 16:55
  • 1
    you used to be able to do this class="{required:true,minlength:2}", but this has been removed and replaced by the data-rule style - https://github.com/jzaefferer/jquery-validation/commit/6df33a8ccc871bbcfafcfc4d5f5658cf63f5e8be – politus Jan 17 '13 at 17:10
0

You can use the built-in rules() method to add rules. See documentation.

This is like the best of both methods. You can avoid defining all the rules with .validate() while still having unlimited flexibility defining custom sets of rules. Then these "sets" of rules can be assigned by a custom class, name, id, etc.

Note: You must call this method after you call .validate(), and it must be combined with an .each().

This method can also be very useful when you are dynamically adding fields to your form.

(Notice that the format is slightly different to defined custom messages than when adding rules within .validate())

jsFiddle DEMO

HTML:

 <input type="text" class="myclass" name="field1" />
 <input type="text" class="myclass" name="field2" />
 <input type="text" class="myclass" name="field3" />

jQuery:

$('form').validate({
    // your other options
});

// the following method must come AFTER .validate()
$('form').find('.myclass').each(function() {
    $(this).rules('add', {
        required: true,
        digits: true,
        range: [1,5],
        messages: {
            required: "Required input",
            digits: "Only digits please",
            range: "Please only enter between {0} and {1}"
        }
    });
});

Alternatively, you can target by field name instead of class...

jsFiddle DEMO

HTML:

 <input type="text" class="myclass" name="field1" />
 <input type="text" class="myclass" name="field2" />
 <input type="text" class="myclass" name="field3" />

jQuery:

$('#form').validate({
    // your other options
});

// the following method must come AFTER .validate()
$("input[name^='field']").each(function() {
    $(this).rules('add', {
        required: true,
        digits: true
    });
});
Sparky
  • 98,165
  • 25
  • 199
  • 285