12

我想为不从 RegularExpressionAttribute 继承但可用于客户端验证的电子邮件地址创建 MVC2 的自定义验证属性。谁能指出我正确的方向?

我尝试了这样简单的事情:

[AttributeUsage( AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false )]
public class EmailAddressAttribute : RegularExpressionAttribute
{
    public EmailAddressAttribute( )
        : base( Validation.EmailAddressRegex ) { }
}

但它似乎不适用于客户。但是,如果我使用 RegularExpression(Validation.EmailAddressRegex)] 它似乎工作正常。

4

4 回答 4

38

您需要为新属性注册一个适配器才能启用客户端验证。

由于RegularExpressionAttribute 已经有一个适配器,即RegularExpressionAttributeAdapter,您所要做的就是重用它。

使用静态构造函数将所有必要的代码保留在同一个类中。

[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple  = false)]
public class EmailAddressAttribute : RegularExpressionAttribute
{
    private const string pattern = @"^\w+([-+.]*[\w-]+)*@(\w+([-.]?\w+)){1,}\.\w{2,4}$";

    static EmailAddressAttribute()
    {
        // necessary to enable client side validation
        DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(EmailAddressAttribute), typeof(RegularExpressionAttributeAdapter));
    }

    public EmailAddressAttribute() : base(pattern)
    {
    }
}

有关更多信息,请查看这篇解释完整过程的帖子。 http://haacked.com/archive/2009/11/19/aspnetmvc2-custom-validation.aspx

于 2011-05-10T18:10:56.063 回答
3

CustomValidationAttribute Class MSDN 页面上现在有一些示例。Phil Haacked 的帖子已过时。

于 2011-03-30T18:34:33.207 回答
0

查看本文中的通用 Dependent Property Validator

于 2011-08-02T14:15:00.460 回答
-2

您是否尝试过使用数据注释?

这是我使用 System.ComponentModel.DataAnnotations 的注释项目;

public class IsEmailAddressAttribute : ValidationAttribute
{
  public override bool IsValid(object value)
  {
    //do some checking on 'value' here
    return true;
  }
}

这是在我的模型项目中

namespace Models
{
    public class ContactFormViewModel : ValidationAttributes
    {
        [Required(ErrorMessage = "Please provide a short message")]
        public string Message { get; set; }
    }
}

这是我的控制器

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult ContactUs(ContactFormViewModel formViewModel)
{
  if (ModelState.IsValid)
  {
    RedirectToAction("ContactSuccess");
  }

  return View(formViewModel);
}

您需要 google DataAnnotations 因为您需要获取项目并编译它。我会这样做,但我需要离开这里很长一段时间。

希望这可以帮助。

编辑

发现这是一个快速的谷歌。

于 2010-03-05T04:39:31.783 回答