User
课程。此类提供数据库中使用的唯一属性。public class User
{
public string Login { get; set; }
public string Password { get; set; }
public DateTime ActiveDateStart { get; set; }
public DateTime ActiveDateEnd { get; set; }
}
User
类的模型
public class UserViewModel: User, IValidatableObject
{
[Required(ErrorMessage = "Enter login")]
[RegularExpression("[a-zA-Z][a-zA-Z0-9]*", ErrorMessage = "Only alpha and digits")]
new public string Login { get; set; }
[Required(ErrorMessage = "Enter password")]
new public string Password { get; set; }
public override IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (ActiveDateStart > ActiveDateEnd)
{
yield return new ValidationResult("Active period start must be before perion end date", new[] { "ActiveDateStart" });
}
}
}
<div class="form-group">
@Html.LabelFor(m => m.Login })
@Html.TextBoxFor(m => m.Login })
@Html.ValidationMessageFor(m => m.Login)
</div>
<div class="form-group">
@Html.LabelFor(m => m.Password })
@Html.PasswordFor(m => m.Password })
@Html.ValidationMessageFor(m => m.Password)
</div>
<div class="form-group">
@Html.LabelFor(m => m.ActiveDateStart })
@Html.TextBoxFor(m => m.ActiveDateStart })
@Html.ValidationMessageFor(m => m.ActiveDateStart)
</div>
<div class="form-group">
@Html.LabelFor(m => m.ActiveDateEnd })
@Html.TextBoxFor(m => m.ActiveDateEnd })
@Html.ValidationMessageFor(m => m.ActiveDateEnd)
</div>
@Html.ValidationSummary()
[HttpPost]
public ActionResult Create(UserViewModel model)
{
if (ModelState.IsValid)
{
// do something
}
return View(model);
}
成功执行通过属性指定的所有验证,并在视图中成功显示所有错误。但是通过IValidatableObject
进行的验证不起作用,也没有显示错误。