ASP.NET MVC data annotations client side validation with inherited RegularExpressionAttribute

前端 未结 2 1906
生来不讨喜
生来不讨喜 2020-12-08 11:09

To keep my model validation clean I would like to implement my own validation attributes, like PhoneNumberAttribute and EmailAttribute. Some of the

2条回答
  •  借酒劲吻你
    2020-12-08 11:47

    You'll need to register a client-side validation adapter for your custom attribute. In this case you can use the existing RegularExpressionAttributeAdapter in System.Web.Mvc, since it should work exactly the same as the standard regex attribute. Then register it when your application start using:

    DataAnnotationsModelValidatorProvider.RegisterAdapter(
        typeof(MailAddressAttribute),
        typeof(RegularExpressionAttributeAdapter));
    

    Should you write an attribute that requires custom client-side validation, you can implement your own adapter by inheriting from DataAnnotationsModelValidator (see also Phil Haack's blog).

提交回复
热议问题