小编Cra*_*per的帖子

自定义RegularExpressionAttribute缺少用于客户端验证的data-val-regex-pattern

我创建了以下自定义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" };
   }
}
Run Code Online (Sandbox Code Playgroud)

ViewModel中的字段使用我的AlphaNumeric属性进行修饰:

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

该字段构建在视图中:

@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)
}
Run Code Online (Sandbox Code Playgroud)

这应该在我的html输入标记上产生适当的 …

data-annotations unobtrusive-validation asp.net-mvc-3 asp.net-mvc-4

5
推荐指数
1
解决办法
6942
查看次数