ASP.NET MVC 自定义验证属性

ASP.NET MVC Custom Validation Attributes

我创建了一个自定义验证属性,用于通过扩展 RegularExpressionAttribute class 以 MM/dd/yyyy 格式验证日期。当我将此属性应用于我的模型中表示日期的字符串 属性 时,它似乎工作正常。但是,我想知道是否可以扩展此验证属性的功能以使其也适用于 DateTime 属性。

这是我的 class 的样子:

[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false)]
public class ValidDateAttribute : RegularExpressionAttribute
{
    private const string pattern = @"((^(10|12|0?[13578])([/])(3[01]|[12][0-9]|0?[1-9])([/])((1[8-9]\d{2})|([2-9]\d{3}))$)|(^(11|0?[469])([/])(30|[12][0-9]|0?[1-9])([/])((1[8-9]\d{2})|([2-9]\d{3}))$)|(^(0?2)([/])(2[0-8]|1[0-9]|0?[1-9])([/])((1[8-9]\d{2})|([2-9]\d{3}))$)|(^(0?2)([/])(29)([/])([2468][048]00)$)|(^(0?2)([/])(29)([/])([3579][26]00)$)|(^(0?2)([/])(29)([/])([1][89][0][48])$)|(^(0?2)([/])(29)([/])([2-9][0-9][0][48])$)|(^(0?2)([/])(29)([/])([1][89][2468][048])$)|(^(0?2)([/])(29)([/])([2-9][0-9][2468][048])$)|(^(0?2)([/])(29)([/])([1][89][13579][26])$)|(^(0?2)([/])(29)([/])([2-9][0-9][13579][26])$))";

    static ValidDateAttribute()
    {
        // necessary to enable client side validation
        DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(ValidDateAttribute), typeof(RegularExpressionAttributeAdapter));
    }

    public ValidDateAttribute()
        : base(pattern)
    {
    }
}

如前所述,当使用如下所示的属性时,一切似乎都已正常工作:

[DisplayName("Date of birth")]
[ValidDate(ErrorMessage = "Invalid date of birth")]
public string DateOfBirth { get; set; }

但是我如何检查验证属性中的数据类型,并且在 DateTime 属性 的情况下,对 DateOfBirth.ToString(MM/dd/yyyy) 应用相同的验证,以便以下内容有效:

[DisplayName("Date of birth")]
[ValidDate(ErrorMessage = "Invalid date of birth")]
public DateTime DateOfBirth { get; set; }

如有任何帮助或建议,我们将不胜感激。谢谢!

如 Michal Franc 在 blogpost 中所述,您可以使用 DisplayFormat 属性在应用正则表达式验证时强制使用特定格式。

[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]

您可以通过以下方式覆盖 IsValid,在验证过程中将值强制为字符串:

public override bool IsValid(object value)
{
   try
   {
      value = value.ToString();
      return base.IsValid(value);
   }
   catch { }
   return base.IsValid(value);
}