Should I implement my validation using the built-in class or the rule?

后端 未结 2 1863
有刺的猬
有刺的猬 2021-01-16 19:33

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

2条回答
  •  不思量自难忘°
    2021-01-16 19:46

    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:

     
     
     
    

    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:

     
     
     
    

    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
        });
    });
    

提交回复
热议问题