6

我创建了以下自定义 RegularExpressionAttribute

[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 ModelClientValidationRule { ErrorMessage =  FormatErrorMessage(metadata.GetDisplayName()), ValidationType = "alphanumeric" };
   }
}

ViewModel 中的字段用我的 AlphaNumeric 属性装饰:

[AlphaNumeric(ErrorMessageResourceType = typeof(Resources), ErrorMessageResourceName = Resources.DriverLicenseNumber_RegexError_)]
public string DriverLicenseNumber { get; set; }

该字段构建在视图中:

@using (Html.BeginForm("Index", "Application", FormMethod.Post, new { id = "applicationDataForm", autocomplete = "off" }))
{
    @Html.LabelFor(m => m.DriverLicenseNumber)
    @Html.ValidationMessageFor(m => m.DriverLicenseNumber)
    @Html.TextBoxFor(m => m.DriverLicenseNumber)
}

这应该在我的 html 输入标签上产生正确的“数据”验证属性。但是,呈现的标签如下所示:

<input data-val="true" data-val-alphanumeric="Please enter a valid driver's license number." id="DriverLicenseNumber" name="DriverLicenseNumber" type="text" value="" maxlength="20" class="valid">

明显不存在应该呈现 的data-val-regexdata-val-regex-pattern属性。

我已经构建了具有完全相同结构的其他验证器,并且它们可以正常工作,例如这个 SSN 验证,它使用 jquery 屏蔽处理屏蔽输入的屏蔽空间:

public class SsnAttribute : RegularExpressionAttribute, IClientValidatable
{
  public SsnAttribute()
  : base("^([0-9]{3}–[0-9]{2}–[0-9]{4})|([ ]{3}–[ ]{2}–[ ]{4})|([0-9]{9,9})$")
{
}

public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
  yield return new ModelClientValidationRule { ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()), ValidationType = "ssn" };
}

}

使用 ViewModel 上的随附应用程序:

[Ssn(ErrorMessageResourceType = typeof(Resources), ErrorMessageResourceName = Resources.SocialSecurity_RegexError_)]
public new string SocialSecurityNumber { get; set; }

该字段构建在视图中:

@using (Html.BeginForm("Index", "Application", FormMethod.Post, new { id = "applicationDataForm", autocomplete = "off" }))
{
    @Html.LabelFor(m => m.SocialSecurityNumber)
    @Html.ValidationMessageFor(m => m.SocialSecurityNumber)
    @Html.TextBoxFor(m => m.SocialSecurityNumber)
}

此验证属性正确呈现 data-val-regex 和 data-val-regex-pattern 属性:

<input class="SSNMask valid" data-val="true" data-val-regex="Please enter a valid social security number." data-val-regex-pattern="^([0-9]{3}–[0-9]{2}–[0-9]{4})|([ ]{3}–[ ]{2}–[ ]{4})|([0-9]{9,9})$" id="SocialSecurityNumber" name="SocialSecurityNumber" type="text" value="" maxlength="22">



我无法弄清楚 AlphaNumeric 属性缺少什么,它没有呈现适当的 html 属性。

4

2 回答 2

10

我相信您遇到的问题AlphaNumericAttribute是您没有为您alphanumeric的验证器类型添加 JavaScript 适配器。

你的代码中肯定有这样的东西:

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

上面的代码声明了客户端适配器SsnAttribute。请注意,它的名称与 的属性中ssn设置的名称相同。ValidationTypeModelClientValidationRule

要解决您的问题,AlphaNumericAttribute您应该返回ModelClientValidationRegexRule,因为它已经为您的案例进行了所有必要的设置(即已经存在的适配器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);
    }
}

但是,如果在正则表达式验证之后的客户端应该有额外的逻辑,你应该编写并注册你自己的不显眼的适配器。

要获得更大的图像并更好地了解如何在 ASP.NET MVC 中实现自定义验证,您可以参考 Brad Wilson Unobtrusive Client Validation in ASP.NET MVC 3的博客文章,请参阅Custom adapters for unusual validators章节。

于 2013-08-04T09:29:41.237 回答
1

这是How to create custom validation attribute for MVC的另一种方法,改编自这篇关于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));
    }
}

通过使用RegisterAdapter,您可以利用已存在的用于您自己继承类型的正则表达式的集成。

于 2015-01-21T01:56:46.307 回答