Show ValidationResult errors in row

Is this a similar question Assign ValidationResult to a specific field?

My view model looks like this:

[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" }); } 

My view is as follows:

  @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> 

But my custom validation error is displayed at the top of the page when I want it to appear in a row.

EG, the error checking the length leads to the display in the line, I would like my confirmation to be performed in the same way.

Thanks Dave

+4
source share
1 answer

There is a validation attribute here that accurately accomplishes what you are trying to achieve with your custom validation. Try adding the Compare attribute:

 [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; } 

Additionally...

Someday I want to add other errors that I want to display using Html.ValidationMessage() . Errors are added to ModelState during server-side validation. The key corresponds to the identifier of the control being checked, but you can also add your own keys.

You can use:

 ModelState.AddModelError("ConfirmPassword", "You've done something wrong..."); 

To add an error to the ConfirmPassword property, which will be displayed with validation errors for ConfirmPassword . Or you can use a different key:

 ModelState.AddModelError("MyError", "You've done something wrong..."); 

You can then display this error in your view using:

 @Html.ValidationMessage("MyError"); 
+5
source

Source: https://habr.com/ru/post/1497303/


All Articles