如何在使用`String`而不是`Date`类型时验证日期?

Voo*_*ild 5 c# asp.net asp.net-mvc types asp.net-mvc-2

在Asp.net MVC应用程序中,我继承了这个问题(如果这是一个问题?),其中一个开发人员使用String了Date类型.

在我的模型中,该属性显示:

[Required]
[DisplayName("Registration Date")]
public string Registrationdate { get; set; }
Run Code Online (Sandbox Code Playgroud)

业务要求是该字段不是必需的,但如果该字段中存在某些内容,则它必须是有效日期.

如何在不更改数据类型的情况下实现此要求?

Bra*_*bby 8

看起来你正在使用它System.ComponentModel.DataAnnotations.使用此库执行此操作的最佳方法是创建新属性以验证日期字符串并将其应用于属性.这里有一些代码供您开始:

[AttributeUsage(AttributeTargets.Property, Inherited = true)]
class DateAttribute : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        var dateString = value as string;
        if (string.IsNullOrWhiteSpace(dateString))
        {
            return true; // Not our problem
        }
        DateTime result;
        var success = DateTime.TryParse(dateString, out result);
        return success;
    }
Run Code Online (Sandbox Code Playgroud)

您可能希望扩展此代码,具体取决于您希望客户端使用哪种字符串.此外,这不会给您任何客户端验证.


Mah*_*aga 6

public string Registrationdate { 
    get; 
    set {
        DateTime date;
        var isDate = DateTime.TryParse(value, out date);
        if (isDate) { 
            _registrationDate = value; 
        }
        else {
          // Throw exception
        }
    }
}
Run Code Online (Sandbox Code Playgroud)