gpt4 book ai didi

使用继承的 RegularExpressionAttribute 进行 ASP.NET MVC 数据注释客户端验证

转载 作者:行者123 更新时间:2023-12-03 12:08:02 25 4
gpt4 key购买 nike

为了保持我的模型验证干净,我想实现我自己的验证属性,比如 PhoneNumberAttributeEmailAttribute .其中一些可以有利地实现为从RegularExpressionAttribute 继承的简单类。 .

但是,我注意到这样做会破坏这些属性的客户端验证。我假设某种类型的绑定(bind)在某处失败。

有什么想法可以使客户端验证正常工作吗?

代码示例 :

public sealed class MailAddressAttribute : RegularExpressionAttribute
{
public MailAddressAttribute()
: base(@"^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$")
{
}
}

最佳答案

您需要为您的自定义属性注册一个客户端验证适配器。在这种情况下,您可以使用 System.Web.Mvc 中现有的 RegularExpressionAttributeAdapter,因为它应该与标准正则表达式属性完全相同。然后在您的应用程序开始使用时注册它:

DataAnnotationsModelValidatorProvider.RegisterAdapter(
typeof(MailAddressAttribute),
typeof(RegularExpressionAttributeAdapter));

如果您编写需要自定义客户端验证的属性,您可以通过继承 DataAnnotationsModelValidator 来实现自己的适配器。 (另见 Phil Haack's blog)。

关于使用继承的 RegularExpressionAttribute 进行 ASP.NET MVC 数据注释客户端验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3627843/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com