MVC 验证和异常处理 重用服务端验证

还记得之前做的自定义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)

    );

}

posted on 2011-03-05 23:27  arg  阅读(513)  评论(0编辑  收藏  举报

导航