zoukankan      html  css  js  c++  java
  • 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)

        );

    }

  • 相关阅读:
    【Linux常用命令】 cat
    【Linux常用命令】 chmod
    【2012.4.22】北京植物园&卧佛寺
    【Linux常用命令】 重定向输出 > 和 >>
    一些话
    linux下查看用户个数和具体名字
    【Linux常用命令】 ls
    Ethernet frame
    防止修改类和方法
    redis数据批量导入导出
  • 原文地址:https://www.cnblogs.com/wusong/p/1971919.html
Copyright © 2011-2022 走看看