使用MVC3和jQuery对整数进行不显眼的验证

yu_*_*sha 2 model-view-controller jquery-plugins unobtrusive-validation asp.net-mvc-3

不显眼的验证不区分数据类型.只有MVC添加到所有数字字段的"数字"验证.

这具有1.2345作为有效整数的不希望的效果.提交时,MVC binder无法解析该值.因此,您可以从服务器获取客户端错误,而不是获取客户端错误.

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

yu_*_*sha 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" }) 
Run Code Online (Sandbox Code Playgroud)

添加了验证适配器(在$(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;
    });
Run Code Online (Sandbox Code Playgroud)

写JavaScript函数isInteger看起来像这样

function isInteger(value) {
    return parseInt(value, 10) == value;
}
Run Code Online (Sandbox Code Playgroud)

现在整数字段给出一个很好的消息"字段必须是一个整数"如果你输入带有小数点的任何东西.

很高兴听到更好的方式.