我已经构建了一个自定义属性,以在客户端验证正十进制值。问题是当我将正则表达式直接应用于属性时,它工作正常,但是当我使用自定义属性时,它不起作用。
工作模式:
[RegularExpression(@"^(?!0?(,0?0)?$)([0-9]{0,3}(,[0-9]{1,2})?)?$", ErrorMessage = "Largura inválida.")]
[Required(ErrorMessage = "Largura obrigatória.")]
[Display(Name = "Formato Aberto")]
public decimal SizeOpenedWidth { get; set; }
自定义属性:
public class PositiveDecimalAttribute : RegularExpressionAttribute
{
public PositiveDecimalAttribute() : base("^(?!0?(,0?0)?$)([0-9]{0,3}(,[0-9]{1,2})?)?$") { }
}
集成在物业中:
[PositiveDecimal(ErrorMessage = "Largura inválida.")]
[Required(ErrorMessage = "Largura obrigatória.")]
[Display(Name = "Formato Aberto")]
public decimal SizeOpenedWidth { get; set; }
在第二个中,客户端验证显示错误消息:
The field Formato Aberto must be a number.
我是否需要在客户端验证中集成新属性?
答案 0 :(得分:4)
您需要在global.asax
中注册您的属性。在其Application_Start()
方法中,添加以下代码:
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(PositiveDecimalAttribute), typeof(RegularExpressionAttributeAdapter));