【问题标题】:Unobtrusive validation for integers with MVC3 and jQuery使用 MVC3 和 jQuery 对整数进行不显眼的验证
【发布时间】:2011-06-24 13:06:29
【问题描述】:

不显眼的验证不区分数据类型。 MVC 仅向所有数字字段添加“数字”验证。

这会产生 1.2345 作为有效整数的不良影响。提交时,MVC binder 无法解析该值。因此,您不会从服务器获取客户端错误。

解决这个问题的最佳方法是什么?有现成的解决方案吗?

【问题讨论】:

    标签: model-view-controller asp.net-mvc-3 jquery-plugins unobtrusive-validation


    【解决方案1】:

    好的,这就是我所做的。

    为 Int32 编写了我自己的 EditorTemplate (Views/Shared/EditorTemplates/Int32.cshtml):

    @model int?           
    @Html.TextBox("", Model.HasValue ? Model.Value.ToString() : "", new { data_val_integer = "Field must be an integer" }) 
    

    添加了一个验证适配器(在 $(document).ready 上运行它:)

    jQuery.validator.addMethod('integer',
        function (value, element, params) {
            return String.IsNullOrEmpty(value) || isInteger(value);
        });
    
    jQuery.validator.unobtrusive.adapters.add("integer", [],
        function (options) {
            options.rules['integer'] = {};
            options.messages['integer'] = options.message;
        });
    

    编写了如下所示的 Javascript 函数 isInteger

    function isInteger(value) {
        return parseInt(value, 10) == value;
    }
    

    现在,如果您键入任何带有小数点的内容,整数字段会给出一个很好的消息“字段必须是整数”。

    很高兴听到更好的方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-03-29
      • 2012-09-09
      • 2012-11-16
      • 1970-01-01
      • 2011-08-15
      • 2023-03-14
      • 1970-01-01
      相关资源
      最近更新 更多