jQuery Validation: Validate form in two parts

前端 未结 1 588
迷失自我
迷失自我 2020-12-22 11:27

I want to validate one form in two part, when I click the btn button then validation is done properly, but when I click btnn it\'s not working and

1条回答
  •  长情又很酷
    2020-12-22 12:17

    By design, you cannot call the .validate() method twice on the same form. The .validate() method is used for initialization and the second instance will always be ignored.

    You have two options here:

    1. Put part 2 into its own
      container.

    OR

    1. Some other trick like showing/hiding the form fields, or using the .rules() method to add/remove rules dynamically depending on which button is clicked. If you're showing/hiding these fields, then declare all rules in the same instance of .validate() and leverage the default behavior of this plugin, which is to ignore all hidden fields.

    Since you have not revealed the working concept of your multi-part form, or the purpose of wanting to validate in two parts, I will show you the simplest solution, which is suggestion #1.

    jQuery:

    $(document).ready(function() {
    
        $("#form1").validate({ // initialize `form1`
            rules: {
                field1: "required"
            },
            messages: {
                field1: "Please specify your name"
            }
        });
    
        $('#btn').click(function() {
            $("#form1").valid();
        });
    
        $("#form2").validate({ // initialize `form2`
            rules: {
                field2: "required"
            },
            messages: {
                field2: "Please specify your name"
            }
        });
    
        $('#btnn').click(function() {
            $("#form2").valid();
        });
    });
    

    HTML:

     
        Field 1: 
    
    
    
    Field 2:

    Here is another answer showing how multi-step forms can be done:

    https://stackoverflow.com/a/20481497/594235

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