【发布时间】: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