我看過這樣的例子很多,而我做的,因爲他們都建議,但我不斷收到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