• 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)

        );

    }

  • 相关阅读:
    《SQL Server 2008从入门到精通》--20180628
    2019国赛
    [蓝桥杯2020] 湖北省省赛
    2019第十届蓝桥杯B组决赛题解第五题
    试题 算法提高 分解质因数
    大数相加减
    试题 算法提高 汉诺塔
    试题 算法提高 欧拉函数
    试题 算法提高 天天向上-dp
    算法训练 猴子吃包子-构造
  • 原文地址:https://www.cnblogs.com/wusong/p/1971919.html
Copyright © 2020-2023  润新知