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

标签 jquery asp.net-mvc

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

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

1 - 我的控制失去焦点。

2- 提交表单。

任何有关我错过的内容的想法将不胜感激!

_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>

在文档就绪功能中应用带有验证 JS 的 Index.cshtml 标记

    <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>

表单标记正文

@{
     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>
}

最佳答案

对于客户端验证,微软使用 jquery.validate.unobtrusive.js 文件。 Client side validation 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:

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

将 UnobtrusiveJavaScriptEnabled 设置为 true 可启用不显眼的 Ajax 和不显眼的客户端验证。当您使用非侵入式验证时,验证规则将转换为 HTML5 属性。 HTML5 属性名称只能包含小写字母、数字和破折号

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

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

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

了解更多信息:

  1. Asp.net MVC validation
  2. MVC client side validation

关于Jquery MVC 4 客户端验证不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15154309/

相关文章:

javascript - 如何检测浏览器高度,减去一定数量的像素,然后输出数字?

asp.net-mvc - ASP.NET MVC FileContentResult 自定义下载对话框?

c# - SubSonic 3.0 简单存储库向对象添加 DateTime 属性

C# 从函数返回不同的类型

php - 使用jquery获取选择元素的值

javascript - 使用 getSelected() 获取所选文本的范围 ID

asp.net-mvc - 根据 HTTP 请求返回 XML 或 JSON

c# - 如何将选定的按钮显示为标签

javascript - 验证 Kendo 中的所有或无文本字段并动态删除消息

javascript - 每个元素的高度如果高于则函数