这是与Assign ValidationResult to specific field?
类似的问题我的视图模型如下所示:
[DisplayName("Password")]
[Required(ErrorMessage = "Password is required")]
[StringLength(3, ErrorMessage = "Password length Should be less than 3")]
public string Password { get; set; }
[DisplayName("Confirm Password")]
[Required(ErrorMessage = "Confirm Password is required")]
[StringLength(3, ErrorMessage = "Confirm Password length should be less than 3")]
public string ConfirmPassword { get; set; }
public static ValidationResult ExtendedValidation(ManageUserViewModel t)
{
if (t.Password == t.ConfirmPassword)
return ValidationResult.Success;
else
return new ValidationResult("Your passwords must match", new[] { "ConfirmPassword" });
}
我的观点如下:
@Html.ValidationSummary(true, "The user details were not saved, please see the validation results below")
@using (Html.BeginForm("Save", "Users", FormMethod.Post))
{
<div class="formField">
@Html.LabelFor(model => model.Password)
@Html.TextBoxFor(model => model.Password)
@Html.ValidationMessageFor(model => model.Password)
</div>
<div class="formField">
@Html.LabelFor(model => model.ConfirmPassword)
@Html.TextBoxFor(model => model.ConfirmPassword)
@Html.ValidationMessageFor(model => model.ConfirmPassword)
</div>
但我的自定义验证错误显示在页面顶部,当我希望它显示在内。
EG,长度检查错误导致内嵌显示,我希望我确认也这样做。
谢谢, 戴夫
答案 0 :(得分:5)
有一个验证属性可以完全满足您的自定义验证要求。尝试添加Compare
属性:
[DisplayName("Password")]
[Required(ErrorMessage = "Password is required")]
[StringLength(3, ErrorMessage = "Password length should be less than 3")]
public string Password { get; set; }
[DisplayName("Confirm Password")]
[Compare("Password", ErrorMessage = "Your passwords must match")]
[Required(ErrorMessage = "Confirm Password is required")]
[StringLength(3, ErrorMessage = "Confirm Password length should be less than 3")]
public string ConfirmPassword { get; set; }
有时我想使用Html.ValidationMessage()
添加我想要显示的其他错误。在服务器端验证期间,错误会添加到ModelState
。该键与正在验证的控件的ID匹配,但您也可以添加自己的键。
您可以使用:
ModelState.AddModelError("ConfirmPassword", "You've done something wrong...");
向ConfirmPassword
属性添加错误,然后会显示ConfirmPassword
的验证错误。或者您可以使用其他密钥:
ModelState.AddModelError("MyError", "You've done something wrong...");
然后,您可以使用以下方式在视图中显示该错误:
@Html.ValidationMessage("MyError");