还记得之前做的自定义email地址合法性验证吗?

public class ValidEmailAddressAttribute : RegularExpressionAttribute

{

    private const string EmailPattern = ".+@.+\\..+";

    public ValidEmailAddressAttribute() : base(EmailPattern)

    {

        // Default message unless declared on the attribute

        ErrorMessage = "{0} must be a valid email address.";

    }

}

DataAnnotationsModelValidatorProvider是无法自动把自定义验证提供给客户端的(近限它自己的四种[Range],[RegularExpression],[Required],[StringLength]),但是,它有四个适配器:

•  RangeAttributeAdapter

•  RegularExpressionAttributeAdapter

•  RequiredAttributeAdapter

•  StringLengthAttributeAdapter

对于继承自RegularExpressionAttribute的自定义验证属性,可以通过这么做,让DataAnnotationsModelValidatorProvider 也支持客户端的ValidEmailAddressAttribute。

protected void Application_Start()

{

    AreaRegistration.RegisterAllAreas();

    RegisterRoutes(RouteTable.Routes);

    DataAnnotationsModelValidatorProvider.RegisterAdapter(

        typeof(ValidEmailAddressAttribute), 

        typeof(RegularExpressionAttributeAdapter)

    );

}

相关文章:

  • 2022-12-23
  • 2022-01-22
  • 2021-11-23
  • 2021-05-17
  • 2022-01-16
猜你喜欢
  • 2021-08-14
  • 2022-01-18
  • 2021-07-24
  • 2021-11-17
  • 2021-05-28
  • 2021-09-23
  • 2021-12-09
相关资源
相似解决方案