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");
source share