4

我正在尝试实现自定义属性验证,类似于 ScottGu 的博客中演示的一个: http://weblogs.asp.net/scottgu/archive/2010/01/15/asp-net-mvc-2-model-validation。 aspx

我有这个电子邮件的自定义验证器属性:

public class EmailAttribute : RegularExpressionAttribute
      {
      public EmailAttribute() :
                base("^[A-Za-z0-9](([_\\.\\-]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([\\.\\-]?[a-zA-Z0-9]+)*)\\.([A-Za-z]{2,})$") { }
      }

我的班级像这样使用它:

    [Required(ErrorMessage = ValidationCiM.MsgObaveznoPolje)]
    [Email(ErrorMessage = ValidationCiM.MsgMailNeispravan)]
    [StringLength(ValidationCiM.LenSrednjePolje, ErrorMessage = ValidationCiM.MsgSrednjePolje)]
    public string Mail { get; set; }

它在服务器端运行良好,模型验证正常,一切正常。但是客户端验证不会为第二个属性激活,它适用于Required,它也适用于StringLength,但不适用于Email。我尝试过同时包含 jquery 和 Microsoft ajax 脚本,但似乎没有区别。

在 ScottGu 的博客中,他指出如果像这样实现自定义验证,则无需添加自定义脚本即可工作。

请问有什么想法吗?

4

2 回答 2

6

在 ASP.NET MVC 3 中使用 IClientValidatable:

 public class EmailAttribute : RegularExpressionAttribute, IClientValidatable
{
    public EmailAttribute()
      :base(@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})$")
    {

    }

    public System.Collections.Generic.IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
      var rule = new ModelClientValidationRegexRule(this.ErrorMessageString, base.Pattern);
      return new[] { rule };
    }
  }
于 2011-05-11T10:45:21.537 回答
3

您实际需要做的是(在应用程序启动时):

DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(EmailAttribute), typeof(RegularExpressionAttributeAdapter));

它将客户端验证连接到您的自定义属性。

于 2011-06-02T12:27:25.150 回答