如何为 MVC 创建自定义验证属性

发布于 2024-08-23 11:40:53 字数 481 浏览 9 评论 0原文

我想为 MVC2 的电子邮件地址创建一个自定义验证属性,该属性不是从 RegularExpressionAttribute 继承,但可以在客户端验证中使用。有人能指出我正确的方向吗?

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

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

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

I'd like to create a custom validation attribute for MVC2 for an email address that doesn't inherit from RegularExpressionAttribute but that can be used in client validation. Can anyone point me in the right direction?

I tried something as simple as this:

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

but it doesn't seem to work for the client. However, if I use RegularExpression(Validation.EmailAddressRegex)] it seems to work fine.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

动听の歌 2024-08-30 11:40:53

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

由于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-验证.aspx

You need to register an adapter for the new attribute in order to enable client side validation.

Since the RegularExpressionAttribute already has an adapter, which is RegularExpressionAttributeAdapter, all you have to do is reuse it.

Use a static constructor to keep all the necessary code within the same class.

[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)
    {
    }
}

For more information checkout this post explaining the complete process.
http://haacked.com/archive/2009/11/19/aspnetmvc2-custom-validation.aspx

怼怹恏 2024-08-30 11:40:53

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

The CustomValidationAttribute Class MSDN page has a few examples on it now. The Phil Haacked post is out of date.

御弟哥哥 2024-08-30 11:40:53

查看这篇文章中的通用从属属性验证器

Look at the universal Dependent Property Validator in this article

叹梦 2024-08-30 11:40:53

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

这是我的注释项目
使用 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);
}

您需要谷歌 DataAnnotations,因为您需要获取项目并编译它。我愿意这么做,但我需要离开这里很长一段时间。

希望这有帮助。

编辑

通过快速谷歌发现了这个。

Have you tried using Data Annotations?

This is my Annotations project
using System.ComponentModel.DataAnnotations;

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

This is in my Models project

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

This is my controller

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

  return View(formViewModel);
}

You'll need to google DataAnnotations as you need to grab the project and compile it. I'd do it but I need to get outta here for a long w/end.

Hope this helps.

EDIT

Found this as a quick google.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文