4

这是一个与 将 ValidationResult 分配给特定字段类似的问题?

我的视图模型如下所示:

    [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,长度检查错误导致在线显示,我希望我的确认也这样做。

谢谢,戴夫

4

1 回答 1

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");
于 2013-08-15T19:55:25.263 回答