Javascript 为 ajax 帖子手动调用 MVC 3 客户端验证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5127813/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 15:46:25  来源:igfitidea点击:

Call MVC 3 Client Side Validation Manually for ajax posts

javascriptjqueryasp.net-mvcvalidationasp.net-mvc-3

提问by Thomas

I am creating an MVC 3 web application. I want to use Data Annotations on my entity class and then use unobtrusive client side validation before making a post back to the server. This works fine when making a regular post. I get validation and the validation summary if any of the fields are not valid. However, I want to post back the information via ajax and json. How can I 'manually' validate the form on the client side first then make my ajax post back to the server. Below is a summarized version of my code.

我正在创建一个 MVC 3 Web 应用程序。我想在我的实体类上使用数据注释,然后在回发到服务器之前使用不显眼的客户端验证。这在发布常规帖子时效果很好。如果任何字段无效,我会得到验证和验证摘要。但是,我想通过ajax和json回发信息。如何首先“手动”验证客户端的表单,然后将我的 ajax 发回服务器。下面是我的代码的总结版本。

  public class Customer
    {
        [Required(ErrorMessage = "The customer's first name is required.")]
        public string FirstName { get; set; }

        [Required(ErrorMessage = "The customer's last name is required.")]
        public string LastName { get; set; }
    }



    <% using (Html.BeginForm()) { %>

    <%: Html.LabelFor(model => model.FirstName, "First Name")%>
    <%: Html.TextBoxFor(model => model.FirstName, new { @class = "TextBox", id = "Customer.FirstName" })%>
    <%: Html.ValidationMessageFor(model => model.FirstName, "*")%>

    <%: Html.LabelFor(model => model.LastName, "Last Name")%>
    <%: Html.TextBoxFor(model => model.LastName, new { @class = "TextBox", id = "Customer.LastName" })%>
    <%: Html.ValidationMessageFor(model => model.LastName, "*")%>

    <div id="CustomerEditSave" class="Button CustomerEditButtons" style="margin-right:40px;">
       <a href="#">Save</a>
    </div>

    <%: Html.ValidationSummary(true) %>

    <% } %>

I have tried this code but it only validates the first name and does not display the validation summary.

我试过这段代码,但它只验证名字,不显示验证摘要。

    $("#CustomerEditSave").click(function () {
        $(form).validate();
        //Ajax call here
    });

回答by Paul

Try:

尝试:

//using the form as the jQuery selector (recommended)
$('form').submit(function(evt) {
    evt.preventDefault();
    var $form = $(this);
    if($form.valid()) {
        //Ajax call here
    }
});

//using the click event on the submit button
$('#buttonId').click(function(evt) {
    evt.preventDefault();
    var $form = $('form');
    if($form.valid()) {
        //Ajax call here
    }
});

This should work with jQuery ajax and MSAjax calls. Could also try using http://nuget.org/packages/TakeCommand.jsor https://github.com/webadvanced/takeCommandit will automatically handle this for you.

这应该适用于 jQuery ajax 和 MSAjax 调用。也可以尝试使用http://nuget.org/packages/TakeCommand.jshttps://github.com/webadvanced/takeCommand它会自动为您处理。

回答by Rob

I have been phaffing about with MVC client side validation for days:

几天来,我一直在谈论 MVC 客户端验证:

Don't use .click use .submit:

不要使用 .click 使用 .submit:

$("#MyForm").on('submit',function () {

    if($("#MyForm").valid())
    {
        //Do ajax stuff
    }

    //Return false regardless of validation to stop form submitting
    //prior to ajax doing its thing
    return false;
});

I'm going add an update to this, consider cancelling the event rather than returning false (or do both):

我将为此添加更新,考虑取消事件而不是返回 false(或两者都做):

$("#MyForm").on('submit',function (e) {

    if($("#MyForm").valid())
    {
        //Do ajax stuff
    }

    e.preventDefault();

    //Return false regardless of validation to stop form submitting
    //prior to ajax doing its thing
    return false;
});

回答by Chris Goodman

At least in my case (MVC 5), it was also necessary to add the following code or else .valid()would always return true:

至少在我的情况下(MVC 5),还需要添加以下代码,否则.valid()将始终返回 true:

$(function () {
$(document).ajaxComplete(function(event, request, settings){
    //re-parse the DOM after Ajax to enable client validation for any new form fields that have it enabled
    $.validator.unobtrusive.parse(document);
});

});

});

See http://johnculviner.com/the-unobtrusive-libraries-client-validation-on-ajax-in-asp-net-mvc-3/

http://johnculviner.com/the-unobtrusive-libraries-client-validation-on-ajax-in-asp-net-mvc-3/

回答by awrigley

IMPORTANT!!:

重要的!!:

Paul's solution is the correct answer to the question, not Dr Rob's.

保罗的解决方案是问题的正确答案,而不是罗伯博士的。

Although you can just use valid() instead of validate().form().

虽然你可以只使用 valid() 而不是 validate().form() 。

But more importantly, there really is no reason to restrict your code as suggested by Dr Rob, ie, not .click and only use .submit. That isn't what solved the problem! What solved the problem was wrapping the $.ajax(...) call in the if statement. Ie:

但更重要的是,确实没有理由按照 Rob 博士的建议来限制您的代码,即不要使用 .click 而只使用 .submit。这不是解决问题的原因!解决问题的是在 if 语句中包装 $.ajax(...) 调用。IE:

if($("#MyForm").valid())
{
    //call to $.ajax or equivalent goes in here.
}

I think that needs clarifying as otherwise the real answer to the problem is obfuscated.

我认为这需要澄清,否则问题的真正答案会被混淆。

回答by Dipak Pandey

$(YourForm).data('unobtrusiveValidation').validate()

$(YourForm).data('unobtrusiveValidation').validate()

回答by mrelva

        if(!$('#myform').data('unobtrusiveValidation').validate())
        {
           // add your extra custom logic
        } 
        else
        { 
             $('#myform').submit(); 
        }

It triggers the validation and returns a boolean, so you can check before submit.

它触发验证并返回一个布尔值,因此您可以在提交之前进行检查。

回答by Squibly

.Valid() works. i.e it tells you whether your form is valid. However alone it does not help to show AND hide messages correctly. here's my manual validation method

.Valid() 有效。即它告诉您您的表格是否有效。然而,单独它无助于正确显示和隐藏消息。这是我的手动验证方法

function validate()
        {
            //valid() not only tells us whether the form is valid but 
            //also ensures that errors are shown !!!
            if ($("form").valid())
            {
                //if the form is valid we may need to hide previously displayed messages
                $(".validation-summary-errors").css("display", "none");
                $(".input-validation-error").removeClass("input-validation-error");
                return true;
            }
            else
            {
                //the form is not valide and because we are doing this all manually we also have to
                //show the validation summary manually 
                $(".validation-summary-errors").css("display", "block");
                return false;
            }
        }

回答by user1810535

I tried all of the above solutions but none worked on MVC5. 

I am using jQuery v2.1.4 and jQuery.Validation v1.11.1. I need to trigger validation while on page render. Only below one worked for me.

我正在使用 jQuery v2.1.4 和 jQuery.Validation v1.11.1。我需要在页面渲染时触发验证。只有以下一种对我有用。

$(document).ready(function () {
   ...
   validateForm();
}

function validateForm() {`enter code here`
    var elem = document.getElementById('btnSave');
    elem.click();    
}

$('#btnSave').click(function (evt) {
    //evt.preventDefault();
    var form = $('form');
    if (form.valid()) {
        //Ajax call here
    }
    //$(".validation-summary-errors").css("display", "block");
});

function Validate() {
    // If no group name provided the whole page gets validated
    Page_ClientValidate();
}