asp.net-mvc 如何为 MVC 创建自定义验证属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2383669/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 00:10:54  来源:igfitidea点击:

How to create custom validation attribute for MVC

asp.net-mvcasp.net-mvc-validation

提问by devlife

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?

我想为 MVC2 创建一个自定义验证属性,用于不继承自 RegularExpressionAttribute 但可用于客户端验证的电子邮件地址。任何人都可以指出我正确的方向吗?

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.

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

回答by JCallico

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.

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

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

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

回答by Chris S

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

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

回答by Satish

Look at the universal Dependent Property Validator in thisarticle

这篇文章中的通用依赖属性验证器

回答by griegs

Have you tried using Data Annotations?

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

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

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

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.

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

Hope this helps.

希望这可以帮助。

EDIT

编辑

Found this as a quick google.

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