我需要验证日期时间对验证是否有效。
Razor MVC3
类
[Range(typeof(DateTime), "1/1/1930", "1/1/2112",
ErrorMessage = "Value for {0} must be between {1} and {2}")]
public DateTime DOB { get; set; }
修改查看表单
<span class="editor-field">
@Html.EditorFor(model => model.DOB)
@Html.ValidationMessageFor(model => model.DOB)
验证会捕获无效日期,但在输入有效日期时不会清除错误,因此表单已挂起。有没有人知道使用验证来检查日期时间是否有效的工作方式?
谢谢,乔
更新了控制器操作
[HttpPost]
public ActionResult Create(Talent talent)
{
talent.Modified = talent.Created = DateTime.Now;
if (talent.DOB < DateTime.Now.AddYears(-100) || talent.DOB > DateTime.Now)
{
talent.DOB = DateTime.Parse("0001/01/01"); talent.Skill = "changed";
return View(talent); }
最终控制者和后期行动
string errorMessageDOB = "DOB is out of range, it needs to be between " + DateTime.Now.AddYears(-100).ToShortDateString()
+ " and " + DateTime.Now.ToShortDateString() + ".";
//
// POST: /Talent/Create
[HttpPost]
public ActionResult Create(Talent talent)
{
talent.Modified = talent.Created = DateTime.Now;
if (talent.DOB < DateTime.Now.AddYears(-100) || talent.DOB > DateTime.Now)
{ ModelState.AddModelError(string.Empty, errorMessageDOB); }