如何为MVC创建自定义验证属性
-
24-09-2019 - |
题
我想为MVC2创建一个自定义验证属性,用于不会从RegulareXpressionAttribute继承的电子邮件地址,但可以在客户端验证中使用。谁能指向正确的方向?
我尝试了这样简单的事情:
[AttributeUsage( AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false )]
public class EmailAddressAttribute : RegularExpressionAttribute
{
public EmailAddressAttribute( )
: base( Validation.EmailAddressRegex ) { }
}
但这似乎对客户不起作用。但是,如果我使用genularexpression(验证。
解决方案
您需要为新属性注册一个适配器,以启用客户端验证。
由于RegulareXpressionAttribute已经具有一个适配器,即RegulareXpressionAttributeDeadapter,因此您要做的就是重复使用它。
使用静态构造函数将所有必要的代码保留在同一类中。
[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
其他提示
CustomValidationAttribute类MSDN页面 现在有一些例子。菲尔·霍克(Phil)的职位已过时。
查看普遍依赖的属性验证器 这个 文章
您是否尝试过使用数据注释?
这是我使用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 DataNannotations,因为您需要获取该项目并进行编译。我会这样做,但我需要在这里长时间结束。
希望这可以帮助。
编辑
不隶属于 StackOverflow