1

我有一个评论表单,其中包含 2 个字段:作者和消息。当我单击提交按钮时,验证不会触发。如果我再次单击提交按钮,则验证有效。知道为什么吗?

//User Clicked Submit Button
$('#CommentsForm').live('submit', function (e) {
    e.preventDefault(); //Prevent Browser from getting new url

    //Validate the comments form
    $('#CommentsForm').validate({
        rules: {
            Author: "required",
            Message: "required"
        },
        messages: {
            Author: "Author is required.",
            Message: "Comment is required."
        },
        errorContainer: "#CommentsErrorBox",
        errorLabelContainer: "#CommentsErrorBox ul",
        wrapper: "li",

        submitHandler: function() {
            //Create JSON object
            var jsonCommentData = {
                ProductID: $('#HiddenProductID').val(),
                Author: $('#Author').val(),
                Message: $('#Message').val()
            };

            //Add the comment.
            $.ajax({
                url: '/Home/_CommentsAdd',
                type: 'POST',
                data: JSON.stringify(jsonCommentData),
                dataType: 'html',
                contentType: 'application/json',

                //The request was a success. Repopulate the div with new result set.
                success: function (data) {
                    $('#AjaxComments').html(data);
                    $('abbr.timeago').timeago(); //update the timestamp with timeago

                    //Change colors of message.                
                    if ($('#CommentStatus').html() == "Your Comment Has Been Added!") {
                        $('#CommentStatus').css('color', 'GREEN');
                    }
                },
                error: function (data) {
                    alert('Fail');
                }
            });
        }
    }); 
});
4

1 回答 1

3

因为您第一次单击#CommentsForm设置 jQuery 验证:

$('#CommentsForm').validate({ ... });

因此,任何后续点击都会被验证。

使固定:

    //setup validation
var form = $('#CommentsForm');

form.validate({ /* ... setup code .... */ }); 

form.live('submit', function (e) {
    e.preventDefault(); //Prevent Browser from getting new url

    $(this).validate();

});
于 2012-05-15T18:57:30.657 回答