ASP.NET MVC自定义验证属性

时间:2015-08-24 16:22:28

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

我已经创建了一个自定义验证属性,用于通过扩展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; }

非常感谢任何帮助或建议。谢谢!

0 个答案:

没有答案