[英]ASP.Net MVC 2.0 Date validation not working
我正在嘗試以dd / mm / yyyy格式驗證日期值,即使我以正確的格式輸入日期也收到錯誤消息。
這是我的代碼:
[Required(ErrorMessage = "Required Field.")]
[RegularExpression(@"^((0[1-9])|([1-2][0-9])|3[0-1])\/((0[1-9])|(1[0-2]))\/[0-9]{4}$",ErrorMessage="Please enter in dd/mm/yyyy")]
[DataType(DataType.Date,ErrorMessage="Please enter date.")]
public DateTime BeginningDate { get; set; }
您收到的錯誤消息來自模型綁定程序,它與屬性沒有共同之處。 我認為,如果要檢查正則表達式,應使用:
public string BeginningDate { get; set;}
然后在模型綁定之后將其自己轉換為DateTime
。 您知道必須以特定格式提供日期,但是模型活頁夾不是那么聰明,它使用web.config / server設置,並且會引發錯誤。 用正則表達式檢查DateTime
類型沒有意義,因為它已經是DateTime,而不是字符串。 首先進行模型綁定,然后進行驗證。
public class DateRegexAttribute : RegularExpressionAttribute, IClientValidatable
{
public DateRegexAttribute(string pattern)
: base(pattern)
{
}
public override bool IsValid(object value)
{
DateTime date;
try
{
date = (DateTime) value;
}
catch
{
return false;
}
var input = date.Date.ToShortDateString();
Match match = Regex.Match(input, Pattern, RegexOptions.IgnoreCase);
return match.Success;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRegexRule(ErrorMessageString, Pattern);
return new[] { rule };
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.