加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

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

发布时间:2020-12-16 04:21:14 所属栏目:asp.Net 来源:网络整理
导读:我正在尝试继承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
我正在尝试继承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中添加以下行以将Adaptiveater与您的自定义属性相关联,该属性将负责发出客户端验证属性:
DataAnnotationsModelValidatorProvider.RegisterAdapter(
    typeof(SsnAttribute),typeof(RegularExpressionAttributeAdapter)
);

您需要这个的原因是RegularExpressionAttribute的实现方式.它没有实现IClientValidatable接口,而是具有与之关联的RegularExpressionAttributeAdapter.

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

这是个人说的,我没有看到实现这个自定义验证属性的重点.在这种情况下,常量可能就足够了:

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; }
}

看起来很可读.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读