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

dev*_*ife 12 asp.net-mvc asp.net-mvc-validation

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

我尝试了一些简单的事情:

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

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

JCa*_*ico 36

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

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

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