且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

自定义的正前pression没有验证在客户端

更新时间:2023-09-13 23:52:10

您需要的Global.asax 注册您的属性。在其的Application_Start()方法,添加以下code:

DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(PositiveDecimalAtt‌​ribute), typeof运算(RegularEx pressionAttributeAdapter));

I have build a custom attribute to validate on the client side a positive decimal value. The problem is that when I apply the regular expression directly to the property, it works fine, but when I use the custom attribute, it does not work.

Working mode:

    [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; }

Custom Attribute:

public class PositiveDecimalAttribute : RegularExpressionAttribute
{
    public PositiveDecimalAttribute() : base("^(?!0?(,0?0)?$)([0-9]{0,3}(,[0-9]{1,2})?)?$") { }
}

Integrated in the property:

    [PositiveDecimal(ErrorMessage = "Largura inválida.")]
    [Required(ErrorMessage = "Largura obrigatória.")]
    [Display(Name = "Formato Aberto")]
    public decimal SizeOpenedWidth { get; set; }

In the second one, client side validation presents the error message:

The field Formato Aberto must be a number.

Do I need to integrate the new attribute on the client side validation?

You need to register your attribute in global.asax. In its Application_Start() method, add the following code:

DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(PositiveDecimalAtt‌​ribute), typeof(RegularExpressionAttributeAdapter));