【发布时间】:2016-04-25 16:27:59
【问题描述】:
我已经构建了一个自定义属性来在客户端验证正十进制值。问题是当我将正则表达式直接应用于属性时,它可以正常工作,但是当我使用自定义属性时,它就不起作用了。
工作模式:
[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.
是否需要在客户端验证中集成新属性?
【问题讨论】:
-
你在
global.asax注册了吗? -
您好,谢谢,不。我必须在 global.asax 中包含什么?
-
在
Application_Start()- 添加DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(PositiveDecimalAttribute), typeof(RegularExpressionAttributeAdapter)); -
就这样? :) 它的工作!我必须为每个自定义属性都这样做吗?
-
如果它继承自现有的
RegularExpressionAttribute,那么是的
标签: c# regex asp.net-mvc validation