multiple jquery validators on one form

2020-08-04 10:31发布

问题:

I'm using jquery.validate plugin and facing the following situation:

<form id="myForm" ....>
    <input type="text" id="value1"/>

    <!-- Here is some code rendered from the partial -->
    <script type="text/javascript">
    $(document).ready(function() {
        var validator = $('#myForm').validate({
            rules: {
                value_from_partial: {
                    required: true
                }
            },
            messages: {
                value_from_partial: {
                    required: "Enter your firstname"
                }
            },
            submitHandler: function() {
                alert("submitted!");
            }
        });
    });
    </script>
    <input type="text" id="value_from_partial"/>
    <!-- End of code rendered from the partial -->
</form>
<script type="text/javascript">
    $(document).ready(function() {
        var validator = $('#myForm').validate({
            rules: {
                value1: {
                    required: true
                }
            },
            messages: {
                value1: {
                    required: "Enter your firstname"
                }
            },
            submitHandler: function() {
                alert("submitted!");
            }
        });
    });
</script>

Validation added in the partial doesn't work. When I remove .validate from the main html, then validation in the partial works. It seems that jquery.validate doesn't allow that there are two .validate calls on the same form. On the other hand, I can not call "add" rules for validator, since I want my validation code to come from the partial itself (which is actually a plugin). Is there any way to include my validation logic together with the partial, and to use jqury.validate instead of manual validation. Is there any other validation framework that can allow this? Thanks!

回答1:

You're correct that you can't call validate() twice. Well, you can, but the options have no effect the second time.

Two options:

  1. Build your rules in HTML instead of JavaScript. For example, add the required class to an input instead of adding a required rule. The validator supports this.
  2. Have the "partial" and "main" parts of the form build up an options object and then call validate in a single ready event, passing this object, instead of calling validate twice.


回答2:

If you are breaking a large form into multiple parts, then why not make each part its own form? As each section is completed you can carry forward the values using hidden inputs in the final form, or better yet assigning session variables.



回答3:

Before your partial is loaded you could try making validator a global variable.

var validator;

Next you would want to try and unbind the submit method of the first call to validate() inside your second document.ready block:

$('#myForm').unbind('submit');