jQuery Validate set rule using wildcard to find target fields

后端 未结 1 1650
梦谈多话
梦谈多话 2020-12-22 10:37

Is there possibility to add rules by wildcard? I think it\'s not possible to set rules like this...

$(\"#form\").validate({
        // errorLabelContainer:         


        
相关标签:
1条回答
  • 2020-12-22 11:12

    Use the built-in rules() method to add rules. See documentation.

    Note: You must call this method after you call .validate().

    jsFiddle DEMO

    $("#form").validate({
        errorElement: "p",
        errorClass: "form-error"
    });
    
    // the following method must come AFTER .validate()
    $("input[name*='x.child']").each(function() {
        $(this).rules('add', {
            required: true,
            minlength: 5
        });
    });
    

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

    The following to combine with custom messages:. Note that the format is slightly different than when adding rules as options within .validate()...

    $("input[name*='x.child']").each(function() {
        $(this).rules('add', {
            required: true,
            minlength: 5,
            messages: {
                required: "Required input",
                minlength: jQuery.format("At least {0} characters are necessary")
            }
        });
    });
    

    As mentioned elsewhere, you can also create a class and use like this...

    jsFiddle DEMO

    HTML:

    <input type="text" class="myclass" name="whatever" />
    

    jQuery:

    $("#form").validate({
        errorElement: "p",
        errorClass: "form-error"
    });
    
    // the following method must come AFTER .validate()
    $('#form').find('.myclass').each(function() {
        $(this).rules('add', {
            required: true,
            minlength: 5,
            messages: {
                required: "Required input",
                minlength: jQuery.format("At least {0} characters are necessary")
            }
        });
    });
    
    0 讨论(0)
提交回复
热议问题