asp.net-mvc-3 - 使用掩码验证整数输入 (Asp .NET MVC 3.0)

标签 asp.net-mvc-3 jquery-validate maskedinput

我的模型:

public virtual int? NumberTest { get; set; }

我的观点

@Html.LabelFor(model => model.NumberTest)
<br />
@Html.TextBoxFor(model => model.NumberTest)

我正在使用Masked Input Plugin ,所以我的 View 中有:

$("#NumberTest").mask("99999-999");

我生成的 Html :

<input data-val="true" data-val-number="The field NumberTest must be a number." id="NumberTest" name="NumberTest" type="text" value="" />

因此它会自动对我的整数输入生成数字验证...并且我使用带有非整数字符的掩码来格式化数字...

当我填写输入时,总是会调用此验证器...我该如何解决这个问题?

最佳答案

我所做的是将数据类型设置为字符串,以便它可以与 maskedinput 一起使用,但随后在自定义模型绑定(bind)器中,我删除了所有非数字字符,以便它可以作为 int 保存到数据库中。您仍然可以获得客户端和服务器端保护,因为客户端的 maskedinput 会阻止用户输入非数字字符,并且服务器端会过滤掉潜在的错误字符。

这是自定义模型绑定(bind)器代码:

public class CustomModelBinder : DefaultModelBinder
{
    protected override void SetProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, object value)
    {
        if (value != null && propertyDescriptor.PropertyType == typeof(string))
        {
            // always trim strings to clean up database padding
            value = ((string)value).Trim();

            if ((string)value == string.Empty)
            {
                value = null;
            }
            else if ((propertyDescriptor.Attributes[typeof(PhoneNumberAttribute)] != null
                || propertyDescriptor.Attributes[typeof(ZipCodeAttribute)] != null
                || propertyDescriptor.Attributes[typeof(SocialSecurityNumberAttribute)] != null)
                && bindingContext.ValueProvider.GetValue(propertyDescriptor.Name) != null
                && bindingContext.ValueProvider.GetValue(propertyDescriptor.Name).AttemptedValue != null)
            {
                value =
                    Regex.Replace(bindingContext.ValueProvider.GetValue(propertyDescriptor.Name).AttemptedValue,
                                  "[^0-9]", "");
            }
        }

        base.SetProperty(controllerContext, bindingContext, propertyDescriptor, value);
    }
}

自定义属性只是空属性:

public class ZipCodeAttribute : Attribute { }

在 View 模型中,只需像这样标记您的字段:

[ZipCode]
public string Zip { get; set; }

以下是如何执行 whole thing with maskedinput, editor templates and unobtrusive validation .

关于asp.net-mvc-3 - 使用掩码验证整数输入 (Asp .NET MVC 3.0),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6472098/

相关文章:

c# - 获取适用于 EF6 的最新版本 MySQL

ajax - 没有表单标签的 ASP.NET MVC3 客户端验证

jquery - 拦截提交按钮的点击并检查表单 jQuery 的有效性

javascript - 使用掩码在输入上键入方向

c# - 如何将 LINQ to SQL Distinct() 运算符应用于 List<T>?

IIS7 上的 ASP.NET 身份验证问题 - Windows 身份验证的 User.Identity.Name 为空

asp.net-mvc-3 - 如何设置新的成员资格和 session 提供程序以在 Windows Azure 中运行?使用 MVC3 和 Web 角色

jquery - 如何抑制 jquery 验证取消?

javascript - 在循环中运行时 undefined object ,但在顺序执行时未定义

jquery - jQuery 验证和屏蔽输入之间的冲突