2

这是场景。

用户填写表格。他忘记了一些必要的信息。我的验证码向用户表明缺少的字段是必需的。他完整填写表格并提交。它的工作原理。

现在,用户手动删除必填字段并再次点击提交。Presto 它可以工作(它应该)。如何让我的验证再次生效以防止提交空字段?这是我的代码。它仅适用于表单提交的 1 次迭代。所有后续提交都会忽略我的验证。

谢谢...

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

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

    //Create JSON object
    var jsonCommentData = {
        ID: $('#HiddenID').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');
        }
    });
});

这是我的部分观点:_Comments

@model DH.ViewModels.CommentsViewModel

<div id="AjaxComments">
@{
    <input type="hidden" id="HiddenPageNumber" value="@Model.PageNumber.ToString()" />
    <input type="hidden" id="HiddenPageCount" value="@Model.PageCount.ToString()" />

    //No Comments Yet
    if (Model.CommentStatus.Length > 0)
    {
            <div id="CommentStatus">@Model.CommentStatus</div>
    }

    foreach (var item in Model.Comment)
    {   
        <div class="CommentContainer">
            <div class="RateComment">
                <img src="/content/images/icons/Thumbs-Up-16x16.png" alt="Thumbs Up" title="Uprate Comment" style="margin-top: 10px;" />
                <div class="CommentRating">8</div>
                <img src="/content/images/icons/Thumbs-Down-16x16.png" alt="Thumbs Down" title="Downrate Comment" style="margin-top: 5px;" />
            </div>
            <div class="CommentHeader">
                <div class="CommentAuthor">@item.Author</div>
                <div class="MessageDate">
                    <img src="/content/images/icons/Clock-16x16.png" width="16" height="16" alt="Comment Time" style="vertical-align: middle; padding-bottom: 2px;" />
                    <abbr class="timeago" title="@item.MessageDate" style="border-bottom-width: 0;">@item.MessageDate</abbr>
                </div>
            </div>
            <div class="CommentMessage">@item.Message</div>
            <div style="clear: both;"></div>
        </div>
    }
}

<div id="Pagination">
@{ 
    //Setting up Increments of 10 Pagination links
    int StartPage;
    int EndPage;
    int PageNumber = Model.PageNumber;
    int PageCount = Model.PageCount;

    if (PageCount < 10) {
        StartPage = 1;
        EndPage = PageCount;
    }
    else {
        if (PageNumber < 10) {
            StartPage = 1;
            EndPage = 10;
        }
        else {
            StartPage = PageNumber - 5;
            EndPage = PageNumber + 4;
            if (EndPage > PageCount) {
                EndPage = PageCount;
                StartPage = EndPage - 9;
            }
        }
    }

    //Display "Page of" if there are comments.
    if (@Model.PageCount > 0)
    {
        <div id="PageOf">Page @Model.PageNumber of @Model.PageCount</div>
    }

    //Set up First and Prev arrow links
    if (Model.PageNumber > 1) {
        <a class="PaginationLink" title="Prev" href="">< Prev</a>
    }

    //Loop through and create the page #'s.
    for (var PageCounter = StartPage; PageCounter <= EndPage; PageCounter++) {
        //Display the Page # in a Black Box
        if (PageCounter == PageNumber) {
            <span class="CurrentPage">@PageNumber</span>
        }
        //Create the Page # Links.
        else {
            <a class="PaginationLink" title="@PageCounter" href="">@PageCounter</a>
        }
    }

    //Set up Next and Last arrow links
    if (Model.PageNumber < Model.PageCount) {
        <a class="PaginationLink" title="Next" href="">Next ></a>
    }
} 
</div>

<div id="CommentsFormContainer">
    <form id="CommentsForm" action="">
    <div id="CommentsErrorBox"><ul></ul></div>
    <fieldset id="CommentsFormFieldset">
        <legend id="CommentsFormLegend" align="center">Add a Comment</legend>
        <label for="Author" class="LabelAuthorMessage">Author:&nbsp;</label><input type="text" id="Author" name="Author" size="30" class="CommentInputs" />
        <label for="Message" class="LabelAuthorMessage">Comment:&nbsp;</label><textarea id="Message" name="Message" cols="35" rows="5" class="CommentInputs"></textarea>
        <input type="text" id="CharCount" value="0" readonly="readonly" />&nbsp;&nbsp;
        <label for="CharCount" id="LabelCharCount">* Max 200 Characters</label>
        <input type="submit" id="SubmitComment" value="Submit" name="SubmitComment" style="float: left; margin-left: 50px;" />
    </fieldset>
    </form>
</div>

4

1 回答 1

2

您的问题完全在于您的实施。

当页面加载时会发生以下情况,这使您的表单在第一次提交时成功工作......

var validator = form.validate({
    rules: {
        Author: "required",

        etc....

然后,因为您再次将它包含在提交处理程序中,所以它在这里重新初始化......

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

    $(this).validate();

...这打破了下一次提交。

您需要做的就是初始化一次(包括所有选项),而不是在提交处理程序中......

$('#CommentsForm').validate({
    rules: {
        Author: "required",

        etc....

参考这些官方demo的源码。


编辑:

同样,您不需要提交处理程序,因为它会干扰您的表单提交。

换句话说,您的验证工作正常,但是当您点击“提交”时,您的外部提交处理程序函数将完全接管,因此验证随后开始失败也就不足为奇了。

正如我在原始评论中提到的,验证插件有一个内置的提交处理程序来处理包括您的 ajax 在内的所有内容。

彻底删除这一切...

form.live('submit', function (e) { ....

然后您的validate()函数中,您只需根据作为第二个选项列出的插件文档添加一个提交处理程序...

$('#CommentsForm').validate({
    rules: {
        Author: "required",

        /// etc....

    },

    submitHandler: function(form) {

        /// put all your ajax and such in here

    }

 });
于 2012-05-15T22:46:33.997 回答