3

我尝试在提交请求之前验证表单。我正在使用 jquery 验证

我期待页面完成加载时,表单将自动提交,我将在 div 中看到“正在加载”。但这里什么都没有发生是我的代码。但似乎它不起作用..

<script type="text/javascript">

    function submitForm() {
        $('#SearchForm').validate({
            errorLabelContainer: "#ErrorLabel",
            rules: {
                instrument: {
                    required: true,
                    maxlength: 10
                }
            },
            messages: {
                maxlength: "Must no longer than 10 characters",
                required: "Must not be empty"
            },

            submitHandler: function () { $('#SearchForm').submit(); }
        });
    }

    $(document).ready(function () {
        $('#SearchForm').submit(function () {
            $('#DivToUpdate').text('Loading ...');
        });
        submitForm();
    });
</script>

4

2 回答 2

4

做了一个小工作演示 http://jsfiddle.net/CRfuZ/

2件事:尝试推杆invalidHandlerform传给submitHandler

在上面的演示中,如果您输入更多,那么maxlenght 10halbert ininvalidHandler将捕获它。

休息随意玩演示。

希望这会有所帮助:)

链接:http ://docs.jquery.com/Plugins/Validation/validate

代码

jQuery(function($) {
    $("#form").validate({
        debug: false,
        focusInvalid: false,
        onfocusout: false,
        onkeyup: false,
        onclick: false,
        rules: {
            instrument: {
                required: true,
                maxlength: 10
            },
        },
        messages: {
            maxlength: "Must no longer than 10 characters",
            required: "Must not be empty"
        },
        success: function(label) {
            alert('succes:' + label);
        },
        submitHandler: function(form) {
            alert('start submitHandler');
            postContent('test');
            alert('end submitHandler');
        },
        invalidHandler: function(form, validator) {
            alert('invalidHandler');
        },
    });
});


function postContent(postData) {
    alert('postcontent: ' + postData);

}


​
于 2012-06-09T09:20:17.820 回答
1

使用下面编写的代码可能会解决您的问题...

<script type="text/javascript">
    jQuery(function ( $ ) {
            var $theForm = $( 'form' );
        $( '#DivToUpdate' ).text( 'Loading ...' );
        $theForm.validate({
            rules: {
                instrument : {
                    required: true,
                    maxlength: 10
                }
            }, messages: {
                maxlength : "Must no longer than 10 characters",
                required : "Must not be empty"
            }
        });
        if( $theForm.valid() ) {
            $theForm.submit(); //submitting the form
        }
    });
</script>

你不应该submitHandler一般使用...

补充:在jsfiddle运行示例。

于 2012-06-09T09:26:27.503 回答