rjv
rjv

Reputation: 6776

Add single validation message for multiple fields

I have a password reset page that looks like this

enter image description here

I have a validation that verifies whether the new password has been used recently.

The requirement is that if the password has been used recently, then mark both new password and confirm password fields as erroneous and display validation message as follows.

enter image description here

How can I add a single validation message for the two fields?

I tried this

ModelState.AddModelError(newpasswordfieldname, "");
ModelState.AddModelError(confirmpasswordfieldname, AccountResources.FailMinPasswordHistory);

but that displayed an error "The value password is invalid." for the new password field.

Is there any way to achieve this, other than using TempData/ViewData, ie, using the native form validation SDK?

Upvotes: 1

Views: 2008

Answers (2)

rjv
rjv

Reputation: 6776

Since I found no solution using the Native MVC validation SDK, I was forced to use a dirty workaround.

In my controller

ModelState.AddModelError(newpasswordfieldname, "DONOTSHOW");
ModelState.AddModelError(confirmpasswordfieldname, AccountResources.FailMinPasswordAge);

And in my view

@if(ViewData.ModelState["NewPassword"]!=null && 
    ViewData.ModelState["NewPassword"].Errors.First().ErrorMessage!="DONOTSHOW")
{
    @Html.ValidationMessageFor(model => model.NewPassword)
}

Upvotes: 1

DDan
DDan

Reputation: 8286

Did you try to use the AddModelError(String, String) overload?

ModelState.AddModelError(newpasswordfieldname, "This password was used too recently");
ModelState.AddModelError(confirmpasswordfieldname, "This password was used too recently");

Add the same custom message to both properties.

Upvotes: 0

Related Questions