Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom ErrorMessage for Compare attribute does not work

Steps to reproduce:

  1. Create a new MVC 5 project with Individual User Accounts.
  2. Look at the ErrorMessage specified in RegisterViewModel for the ConfirmPassword property. It is "The password and confirmation password do not match.".
  3. Build and run the application, and try to register with non-matching passwords. I'll se the error message "'Confirm password' and 'Password' do not match.", instead of the one specified in the model.

It seems like a custom ErrorMessage property on the Compare attribute isn't working. Even if I specify a ErrorMessage, the validation still shows some sort of default message instead.

This work with System.Web.Mvc.CompareAttribute, but this is now deprecated and you should instead use System.ComponentModel.DataAnnotations.CompareAttribute, which shows this problem.

I add the Compare attribute to a property and specify the ErrorMessage as follows:

[Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match. I'll even add some random text!")]
public string ConfirmPassword { get; set; }

the expected result would be (but this isn't what I get):

Expected result with custom ErrorMessage

Instead, I get this "default" error message:

Actual result with standard ErrorMessage

Client side validation is disabled. Am I missing something? This example is taken from the MVC 5 template with Individual User Accounts as authentication.

like image 303
JLe Avatar asked Nov 14 '13 12:11

JLe


3 Answers

I have same problem, solution:

Change:

[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]

To:

[System.Web.Mvc.Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]

It's working!

like image 176
vietdv Avatar answered Oct 19 '22 20:10

vietdv


I think this is a bug. (Edit: It is.) I'm also able to reproduce this. In fact, the behaviour is exactly the same with client-side validation turned on. If you take a look at the generated HTML, you'll see it's not even generating the custom error string - it always emits the default one.

Actually, I've just had a search around to find more information and I've found it has been submitted as a bug on codeplex. It was reported 8 days ago and someone has been assigned to it. You can find the bug report here.

like image 45
John H Avatar answered Oct 19 '22 19:10

John H


It's an old bug from 2013. Try the following command to update all of the project's dependencies:

PM> update-package
like image 7
VahidN Avatar answered Oct 19 '22 19:10

VahidN