gpt4 book ai didi

asp.net-mvc - 尝试继承RegularExpressionAttribute,不再验证

转载 作者:行者123 更新时间:2023-12-02 06:45:17 24 4
gpt4 key购买 nike

我正在尝试继承 RegularExpressionAttribute 以通过验证 SSN 来提高可重用性。

我有以下模型:

public class FooModel
{
[RegularExpression(@"^(?!000)(?!666)(?!9[0-9][0-9])\d{3}[- ]?(?!00)\d{2}[- ]?(?!0000)\d{4}$", ErrorMessage = "The SSN you entered is invalid. If you do not have this number please leave the field blank")]
public string Ssn { get; set; }
}

这将在客户端和服务器上正确验证。我想将冗长的正则表达式封装到它自己的验证属性中,如下所示:

public class SsnAttribute : RegularExpressionAttribute
{
public SsnAttribute() : base(@"^(?!000)(?!666)(?!9[0-9][0-9])\d{3}[- ]?(?!00)\d{2}[- ]?(?!0000)\d{4}$")
{
ErrorMessage = "SSN is invalid";
}
}

然后我改变了我的 FooModel 像这样:

public class FooModel
{
[Ssn(ErrorMessage = "The SSN you entered is invalid. If you do not have this number please leave the field blank")]
public string Ssn { get; set; }
}

现在验证不会在客户端上呈现不显眼的数据属性。我不太确定为什么,因为这似乎两者本质上应该是同一件事。

有什么建议吗?

最佳答案

在您的 Application_Start 中添加以下行,将适配器与负责发出客户端验证属性的自定义属性相关联:

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

您需要它的原因是 RegularExpressionAttribute 的实现方式。它没有实现 IClientValidatable 接口(interface),但它有一个与其关联的 RegularExpressionAttributeAdapter

在您的情况下,您有一个派生自 RegularExpressionAttribute 的自定义属性,但您的属性没有实现 IClientValidatable 接口(interface)以便客户端验证正常工作,也没有与其关联的属性适配器(与其父类相反)。因此,您的 SsnAttribute 应该实现 IClientValidatable 接口(interface),或者按照我之前的回答中的建议关联一个适配器。

就我个人而言,我认为实现此自定义验证属性没有多大意义。在这种情况下,一个常量可能就足够了:

public const string Ssn = @"^(?!000)(?!666)(?!9[0-9][0-9])\d{3}[- ]?(?!00)\d{2}[- ]?(?!0000)\d{4}$", ErrorMessage = "The SSN you entered is invalid. If you do not have this number please leave the field blank";

然后:

public class FooModel
{
[RegularExpression(Ssn, ErrorMessage = "The SSN you entered is invalid. If you do not have this number please leave the field blank")]
public string Ssn { get; set; }
}

看起来很可读。

关于asp.net-mvc - 尝试继承RegularExpressionAttribute,不再验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18666812/

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