【问题标题】:Custom RegularExpressionAttribute missing data-val-regex-pattern for client-side validation自定义 RegularExpressionAttribute 缺少用于客户端验证的 data-val-regex-pattern
【发布时间】:2013-07-31 04:00:06
【问题描述】:

我已经创建了以下自定义 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 输入标签上产生正确的 "data-" 验证属性。然而,渲染后的标签是这样的:

<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 属性。

【问题讨论】:

  • 在您的视图中如何/在哪里生成相应的输入字段?你在用Html.TextBoxFor吗?还是Html.EditorFor?这个电话在Html.BeginForm 内吗?能否请您展示一下您的观点?
  • @Darin。我已经更新了我的问题以显示视图中的代码。我将 TextBoxFor 与功能性 SSN 验证器和非功能性 AlphaNumeric 验证器一起使用

标签: asp.net-mvc-3 asp.net-mvc-4 data-annotations unobtrusive-validation


【解决方案1】:

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

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

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

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

要解决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 部分。

【讨论】:

  • 我实际上并没有按照所述为 SsnAttribute 执行 JavaScript,因为它会自动呈现并正确验证。但是,使用 ModelClientValidationRegexRule ( ) 的建议修复确实解决了我的问题!
【解决方案2】:

这是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,您可以利用已经存在的用于您自己继承类型的正则表达式的集成。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-05
    • 1970-01-01
    • 1970-01-01
    • 2017-05-29
    • 1970-01-01
    • 1970-01-01
    • 2015-03-26
    相关资源
    最近更新 更多