【问题标题】:ASP.NET MVC Custom Validation AttributesASP.NET MVC 自定义验证属性
【发布时间】:2015-08-24 16:22:27
【问题描述】:

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

这是我的班级的样子:

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

任何帮助或建议将不胜感激。谢谢!

【问题讨论】:

  • 日期时间属性永远不会是无效日期。所以不需要属性。

标签: c# asp.net asp.net-mvc validation data-annotations


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 谢谢,这似乎已经完成了我打算做的事情(在我修改 .ToString 以匹配我的格式规范之后)。尽管@Juan M. Elosegui 似乎是对的,并且在这种情况下该属性可能是多余的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-04
    • 1970-01-01
    • 2014-11-03
    • 1970-01-01
    • 1970-01-01
    • 2013-11-12
    • 1970-01-01
    相关资源
    最近更新 更多