【问题标题】:client side unobtrusive validation客户端不显眼的验证
【发布时间】:2014-07-04 14:38:14
【问题描述】:

服务器端验证工作正常(一旦我提交表单) 但客户端不起作用。

在我的布局中:

    @Scripts.Render("~/bundles/jqueryval")

捆绑:

 bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                   "~/Scripts/jquery-{version}.js",
                   "~/Scripts/jquery.validate.js",
                   "~/Scripts/jquery.validate.unobtrusive.js"));

在我的配置文件中:

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

我在我的模型和 MVC 5 中使用数据注释

虚拟机:

    public class LocationWorkingHoursVM 
{
    public int LocationID { get; set; }
    public string Name { get; set; }
    [Range(0,1)]
    public decimal?[] Hours { get; set; }
    public string BankHolidays { get; set; }     
}

它被渲染为:

<input class="form-control" data-val="true" data-val-number="The field Nullable`1 must be a number." id="Hours_0_" name="Hours[0]" type="text" value="8.0" />
            <span class="field-validation-valid" data-valmsg-for="Hours" data-valmsg-replace="true"></span>

我错过了什么?

【问题讨论】:

  • 您的控制台是否存在缺少脚本的错误? (FF 或铬)。并且您的数据注释有任何必需的消息和错误消息?
  • 控制台没有错误,没有消息。但是我只是注意到我得到了字段类型的客户端验证。例如。如果我开始在 int 字段中输入字符,它将变为红色。
  • 如果变成红色表示正在做验证,如果你想更精确地验证,你需要指定该字段是必需的,如果是必需的,验证应该阻止你发布空的东西或无效。例如。 [必填(ErrorMessage = "此字段为必填项")]
  • 客户端验证仅适用于该类型。例如。我添加了以下注释 [Range(0, 1],但它没有发生在客户端上
  • 例如 atm 一旦我从一个输入字符的数字框中跳出。盒子会变红。是否有可能具有具有数据注释的相同行为?

标签: c# javascript asp.net-mvc unobtrusive-validation


【解决方案1】:

这是因为我使用自己的 EditorFor 助手模板。但是我把它定义为

TextBoxFor(r=>r.model, new { @class= "foo")})

是否可以使用我的模板使其工作?

【讨论】:

    【解决方案2】:

    尝试将这两行添加到您的主布局中,然后重试

    <script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.12.0/jquery.validate.min.js" type="text/javascript"></script>
    <script src="http://ajax.aspnetcdn.com/ajax/mvc/4.0/jquery.validate.unobtrusive.min.js" type="text/javascript"></script>
    

    【讨论】:

      【解决方案3】:

      如果您使用的是 jQuery 1.9.1 或更高版本,请确保您使用的是

      jQuery 验证(至少 1.11.1) Microsoft jQuery Unobtrusive Validation(至少 2.0.30116.0) Microsoft jQuery Unobtrusive Ajax(至少 2.0.30116.0)

      MVC data annotations range validation not working properly

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-02-19
        • 1970-01-01
        • 2012-07-11
        • 1970-01-01
        • 2012-04-15
        • 1970-01-01
        • 2011-05-10
        • 2011-07-22
        相关资源
        最近更新 更多