2

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

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

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

4

1 回答 1

5

好的,这就是我所做的。

为 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;
    });

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

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

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

很高兴听到更好的方法。

于 2011-06-24T13:14:47.523 回答