JQuery.Validate adding dynamic rules with messages

后端 未结 3 1286
名媛妹妹
名媛妹妹 2021-02-01 17:42

I have a form on which I am using jquery.validate. I initially call validate with a set of rules and custom messages...

$(\"#formName\").validate( {
  rules: {
          


        
相关标签:
3条回答
  • 2021-02-01 18:29

    $(document).ready(function(){
      $("#controlId").rules("add", {
         required : true,
         messages : { required : 'field is required.' }
      });
    });

    0 讨论(0)
  • 2021-02-01 18:33

    as an answer to this old issue, I do like this to get the meassges inside the rules object.

    After you have added the rules you can add messages like this:

    var inputRules = $('input').rules();
    inputRules.messages = {required: 'your message'};
    

    Good luck!

    0 讨论(0)
  • 2021-02-01 18:36

    Your code seems to be working, without error, as you posted it.

    DEMO with DOM ready: http://jsfiddle.net/UZTnE/

    DEMO with PageInit & jQuery Mobile: http://jsfiddle.net/xJ3E2/

    $(document).on("pageinit", function () {
    
        $('#myform').validate({ // initialize the plugin
            rules: {
                field1: {
                    required: true
                }
            },
            messages: {
                field1: {
                    required: "Enter something"
                }
            }
        });
    
        $('[name*="field"]').each(function () {
            $(this).rules('add', {
                required: true,
                messages: {
                    required: "Enter something else"
                }
            });
        });
    
    });
    

    HTML:

    <form id="myform">
        <input type="text" name="field1" />
        <input type="text" name="field2" />
        <input type="submit" />
    </form>
    

    BTW:

    this...

    ignore: null, // include hidden fields
    

    should be...

    ignore: [], // include hidden fields
    

    See: jQuery Validate - Enable validation for hidden fields

    0 讨论(0)
提交回复
热议问题