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

陌路散爱 提交于 2019-12-01 06:05:40

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.

KyleMit

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!