我创建了以下自定义 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-regex和data-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 属性。