Jquery MVC 4 客户端验证不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15154309/
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-26 14:29:15  来源:igfitidea点击:

Jquery MVC 4 Client side Validation Won't Work

jqueryasp.net-mvc

提问by andrewe

I'm trying to use the jQuery validation plugin on a simple MVC 4 application - something I've done in MVC 3 with no problems, but I can't get it working at all.

我正在尝试在一个简单的 MVC 4 应用程序上使用 jQuery 验证插件 - 我在 MVC 3 中做过的事情没有问题,但我根本无法让它工作。

I want the validation to fire when:

我希望在以下情况下触发验证:

1 - my control looses focus .

1 - 我的控制失去了焦点。

2- on form submit.

2-在表单上提交。

Any ideas on what I've missed would be appreciated !

关于我错过的任何想法将不胜感激!

Script references in _Layout.cshtml

_Layout.cshtml 中的脚本引用

<!-- language-all: lang-html -->
<head>
    <meta charset="utf-8" />
    <title>@ViewBag.Title - AWC Web Console</title>
    <link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
    <meta name="viewport" content="width=device-width" />
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
    <script src="@Url.Content("~/Scripts/jquery-1.7.1.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>

</head>

Index.cshtml markup with validation JS applied in Doc ready function

Index.cshtml 标记和验证 JS 应用在 Doc ready 函数中

    <script type="text/javascript">

        $(document).ready(function () {

        alert("doc ready");

        // JQuery client validation
        $("#prodIdFilterForm").validate(
            {
                onsubmit: true,
                rules: {
                    productId_str: {required: true, minlength: 10, number:true }
                },
                messages: { productId_str: "product Id must be entered" },
                // Force validation when control looses focus 
                onfocusout: function (element) {
                    alert("onfocusout");   // not entering this block !
                    $("#productId_str").removeAttr('style');
                    $("#productId_str").valid();   // fire validation
                    $(element).valid();
                }
                ,
                showErrors: function (errorMap, errorList)
                {
                    if (errorList.length > 0)
                    {
                        for (var i = 0; i < errorList.length; i++)
                        {
                            $("#" + errorList[i].element.id).css({ 'background-color': '#FFDFDF' });
                        }
                    }
                }
            }   
            );

    });  // DocReady

</script>

Body of form markup

表单标记的主体

@{
     ViewBag.Title = "Messages";
     Layout = "~/Views/Shared/_Layout.cshtml";
}


@using ( Html.BeginForm("SelectProduct", "WMSMessages", Model, FormMethod.Post, new {  @id = "prodIdFilterForm"} ) )
{
   <fieldset class="filtering">
      <legend>SelectExtensions Product</legend>
      <div>
         <b>Product Id:</b>
         @Html.TextBoxFor(model => model.productId_str, new { @id ="productId_str"}  )

         <div class="filterSubmitBox">
            <input type="submit" value="Show Messages" />
         </div>   
      </div>
   </fieldset>
}

回答by Ravi Gadag

For client side validataion microsoft uses jquery.validate.unobtrusive.js file. Client side validation asp.net mvc

对于客户端验证,微软使用 jquery.validate.unobtrusive.js 文件。 客户端验证asp.net mvc

Enabling Client-Side Validation

To enable client-side validation in ASP.NET MVC 3, you must set two flags and you must include three JavaScript files.

Open the application's Web.config file. Verify that ClientValidationEnabled and UnobtrusiveJavaScriptEnabled are set to true in the application settings. The following fragment from the root Web.config file shows the correct settings:

启用客户端验证

要在 ASP.NET MVC 3 中启用客户端验证,您必须设置两个标志并且必须包含三个 JavaScript 文件。

打开应用程序的 Web.config 文件。验证 ClientValidationEnabled 和 UnobtrusiveJavaScriptEnabled 在应用程序设置中设置为 true。根 Web.config 文件中的以下片段显示了正确的设置:

 <appSettings>
  <add key="ClientValidationEnabled" value="true"/> 
  <add key="UnobtrusiveJavaScriptEnabled" value="true"/> 
 </appSettings>

Setting UnobtrusiveJavaScriptEnabled to true enables unobtrusive Ajax and unobtrusive client validation. When you use unobtrusive validation, the validation rules are turned into HTML5 attributes. HTML5 attribute names can consist of only lowercase letters, numbers, and dashes

将 UnobtrusiveJavaScriptEnabled 设置为 true 可启用不引人注目的 Ajax 和不引人注目的客户端验证。当您使用不显眼的验证时,验证规则将转换为 HTML5 属性。HTML5 属性名称只能由小写字母、数字和破折号组成

for example if you said required attribue for email and with its error message. it will append data-attributes to element like this.

例如,如果您说电子邮件的必需属性及其错误消息。它将像这样将数据属性附加到元素。

 <input data-val="true"
        data-val-required="Email is required (we promise not to spam you!)."
        id="Email" name="Email" type="text" value="" />

Setting ClientValidationEnabled to true enables client-side validation. By setting these keys in the application Web.config file, you enable client validation and unobtrusive JavaScript for the entire application. You can also enable or disable these settings in individual views or in controller methods using the following code:

将 ClientValidationEnabled 设置为 true 将启用客户端验证。通过在应用程序 Web.config 文件中设置这些键,您可以为整个应用程序启用客户端验证和不显眼的 JavaScript。您还可以使用以下代码在单个视图或控制器方法中启用或禁用这些设置:

for more info :

欲了解更多信息:

  1. Asp.net MVC validation
  2. MVC client side validation
  1. Asp.net MVC 验证
  2. MVC 客户端验证