最近在使用MVC4时碰到一个Model验证的问题:整型属性输入非整型字符串时,错误信息总是“字段 XXX 必须是一个数字”,我总觉得这句话读起来很别扭,所以就萌生了要改变这个默认错误提示信息的念头,但我试了还能多办法都没成功,最后在Artech大牛的文章中找到了答案:http://www.cnblogs.com/artech/archive/2012/02/13/NumericPropertyValidation.html
下面简单整理一下处理过程:
1.自定义数值验证属性 NumericAttribute
internal class NumericAttribute : ValidationAttribute, IClientValidatable
{
public override bool IsValid(object value)
{
return true;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
yield return new ModelClientValidationRule { ValidationType = "number", ErrorMessage = this.FormatErrorMessage(metadata.DisplayName)};
}
}
2. 自定义ModelValidatorProvider
将ClientDataTypeModelValidatorProvider提供的NumericModelValidator替换成基于NumericAttribute的DataAnnotationsModelValidator
public class FilterableClientDataTypeModelValidatorProvider : ClientDataTypeModelValidatorProvider
{
public override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, ControllerContext context)
{
var allValidators = base.GetValidators(metadata, context);
var validators = new List<ModelValidator>();
foreach (var v in allValidators)
{
if (v.GetType().Name != "NumericModelValidator")
{
validators.Add(v);
}
else
{
NumericAttribute attribute = new NumericAttribute{ ErrorMessage = Resources.FieldMustBeNumeric};
DataAnnotationsModelValidator validator = new DataAnnotationsModelValidator(metadata, context, attribute);
validators.Add(validator);
}
}
return validators;
}
}
3.注册自定义的ModelValidatorProvider
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
4.补充说明
必须要引用jquery.validate.min.js和jquery.validate.unobtrusive.min.js文件