C# 当使用'String'而不是'date'类型时,如何验证日期?
在Asp.net MVC应用程序中,我继承了这个问题(如果是问题?),其中一个开发人员使用了C# 当使用'String'而不是'date'类型时,如何验证日期?,c#,asp.net,asp.net-mvc,asp.net-mvc-2,types,C#,Asp.net,Asp.net Mvc,Asp.net Mvc 2,Types,在Asp.net MVC应用程序中,我继承了这个问题(如果是问题?),其中一个开发人员使用了String作为日期类型 在我的模型中,属性为: [Required] [DisplayName("Registration Date")] public string Registrationdate { get; set; } 业务要求是该字段不是必需的,但如果该字段中有内容,则该字段必须是有效的日期 在不更改数据类型的情况下,您将如何实现此要求?(某种)伪代码: if (Registrationd
String
作为日期类型
在我的模型中,属性为:
[Required]
[DisplayName("Registration Date")]
public string Registrationdate { get; set; }
业务要求是该字段不是必需的,但如果该字段中有内容,则该字段必须是有效的日期
在不更改数据类型的情况下,您将如何实现此要求?(某种)伪代码:
if (Registrationdate is not empty)
{
RegistrationDateTime = new DateTime(Registrationdate);
if (RegistrationDateTime is not valid DateTime)
fail validation;
}
使用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;
}
}
您可能希望根据希望从客户端获得的字符串类型来扩展此代码。而且,这不会给您任何客户端验证。正则表达式怎么样?数据注释具有regex属性。现在您必须确定一种格式,比如ISO(yyyy/mm/dd),它可能不符合您的要求 另一种选择可能是创建自己的注释 另一个解决方案是使用可为空的datetime(datetime?)。但我不确定该如何处理,因此需要一些尝试和错误。但是,它只需要添加一个?因此,这可能相对容易尝试
Simon可能会使用DateTime.TryParse在setter方法中实现检查。谢谢,这不是一个坏方法。但是如何在MVC应用程序中将其显示为验证错误+1+1:我使用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;
}
}