我看过这样的例子很多,而我做的,因为他们都建议,但我不断收到InvliadCastException
与错误描述:解析字符串日期时间与TryParseExact在C#
无法转换对象类型为“System.DateTime的”输入“System.String”
我让我的日期从一个ASP.NET应用程序MVC4出生文本字段的日期,按以下格式20/09/1986
这里是我的代码,我只想用户abo已经18岁才能注册。
public class AgeValidator : ValidationAttribute
{
public override bool IsValid(object value)
{
string format = "dd/MM/yyyy HH:mm:ss";
DateTime dt;
DateTime.TryParseExact((String)value, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out dt);
DateTime today = DateTime.Today;
int age = today.Year - dt.Year;
if (dt > today.AddYears(-age)) age--;
if (age < 18)
{
return false;
}
return true;
}
}
我自定义的验证,然后使用像这样:
[Required]
[Display(Name = "Date Of Birth")]
[AgeValidator(ErrorMessage="You need to be at least 18 years old to vote.")]
public DateTime DateOfBirth { get; set; }
我怎样才能得到一个DateTime正确解析?
的错误指示'value'已经是'DateTime'对象 – leppie
'value'已经是DateTime了。 –
我认为通过http发布表单发送的所有内容都是字符串?或者Binder为我做了一些聪明的工作? :/ – Ciwan