Custom RegularExpressionAttribute missing data-val-regex-pattern for client-side validation

前端 未结 2 467
独厮守ぢ
独厮守ぢ 2021-01-13 01:56

I have created the following custom RegularExpressionAttribute

[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
pu         


        
2条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-13 02:17

    Here's another approach from How to create custom validation attribute for MVC, which is adapted from this article on ASP.NET MVC Custom Validation:

    [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
    public class AlphaNumericAttribute: RegularExpressionAttribute
    {
        private const string pattern = "^[-A-Za-z0-9]+$";
    
        public AlphaNumericAttribute() : base(pattern)
        {
            // necessary to enable client side validation
            DataAnnotationsModelValidatorProvider.RegisterAdapter(
                typeof(AlphaNumericAttribute), 
                typeof(RegularExpressionAttributeAdapter));
        }
    }
    

    By using RegisterAdapter, you can leverage the integrations that already exist for regular expressions for your own inherited type.

提交回复
热议问题