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

前端 未结 2 465
独厮守ぢ
独厮守ぢ 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:00

    I believe that your issue in case of AlphaNumericAttribute is that you did not added JavaScript adapter for your alphanumeric type of validator.

    You surely have somehting like this in your code:

    $.validator.unobtrusive.adapters.add('ssn', function(options) { /*...*/ });
    

    Above code declares client side adapter for SsnAttribute. Note that it has name ssn which is the same as set in ValidationType property of ModelClientValidationRule.

    To fix issue with AlphaNumericAttribute you should return ModelClientValidationRegexRule as it is already has all necessary setup for your case (i.e. already existing adapter regex).

    [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
    public class AlphaNumericAttribute : RegularExpressionAttribute, IClientValidatable
    {
        public AlphaNumericAttribute()
            : base("^[-A-Za-z0-9]+$")
        {
        }
    
        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            yield return new ModelClientValidationRegexRule(FormatErrorMessage(metadata.GetDisplayName()), Pattern);
        }
    }
    

    But if there should be additional logic on client side behind the regex validation you should write and register your own unobtrusive adapter.

    To get the bigger image and for better undestanding of how custom validation could be implemented in ASP.NET MVC you can reffer to the blog post of Brad Wilson Unobtrusive Client Validation in ASP.NET MVC 3, see Custom adapters for unusual validators section.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题