使用jQuery验证的ASP.Net MVC Ajax表单

Tom*_*han 31 validation ajax asp.net-mvc jquery

我有一个MVC视图,其中包含使用Ajax.BeginForm()辅助方法构建的表单,我正在尝试使用jQuery Validation插件验证用户输入.我得到插件以突出显示无效输入数据的输入,但尽管输入无效,表单也会发布到服务器.

如何停止此操作,并确保仅在表单验证时发布数据?

我的代码


表格:

<fieldset>
    <legend>leave a message</legend>
        <% using (Ajax.BeginForm("Post", new AjaxOptions
           {
               UpdateTargetId = "GBPostList",
               InsertionMode = InsertionMode.InsertBefore,
               OnSuccess = "getGbPostSuccess",
               OnFailure = "showFaliure"
           }))
           { %>
        <div class="column" style="width: 230px;">
            <p>
                <label for="Post.Header">
                    Rubrik</label>
                <%= Html.TextBox("Post.Header", null, new { @style = "width: 200px;", @class="text required" }) %></p>
            <p>
                <label for="Post.Post">
                    Meddelande</label>
                <%= Html.TextArea("Post.Post", new { @style = "width: 230px; height: 120px;" }) %></p>
        </div>
        <p>
            <input type="submit" value="OK!" /></p>
    </fieldset>
Run Code Online (Sandbox Code Playgroud)

JavaScript验证:

$(document).ready(function() {
    // for highlight
    var elements = $("input[type!='submit'], textarea, select");
    elements.focus(function() {
        $(this).parents('p').addClass('highlight');
    });
    elements.blur(function() {
        $(this).parents('p').removeClass('highlight');
    });

    // for validation
    $("form").validate();   
});
Run Code Online (Sandbox Code Playgroud)

编辑:由于我在回答中发布后续问题及其解决方案,这也是工作验证方法...

function ajaxValidate() {
    return $('form').validate({
    rules: {
        "Post.Header": { required: true },
        "Post.Post": { required: true, minlength: 3 }
    },
    messages: {
        "Post.Header": "Please enter a header",
        "Post.Post": {
            required: "Please enter a message",
            minlength: "Your message must be 3 characters long"
            }
        }
    }).form();
}
Run Code Online (Sandbox Code Playgroud)

tva*_*son 32

尝试将一个OnBegin回调添加到AjaxOptions并从回调中返回$('form').validate().form()的值.看看来源,看来这应该有效.

function ajaxValidate() {
   return $('form').validate().form();
}

<% using (Ajax.BeginForm("Post", new AjaxOptions
       {
           UpdateTargetId = "GBPostList",
           InsertionMode = InsertionMode.InsertBefore,
           OnBegin = "ajaxValidate",
           OnSuccess = "getGbPostSuccess",
           OnFailure = "showFaliure"
       }))
       { %>
Run Code Online (Sandbox Code Playgroud)

使用正确的回调名称更新EDIT.