Thứ Hai, 5 tháng 10, 2015

Error message when use Compare Attribute MVC

  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
You have 2 options to solve this bug:
--Option 1
Change:
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
to
[System.Web.Mvc.Compare("Password", ErrorMessage = "Your custom error message")]
--Option 2 (I recommend this one)
We need to update our ASP.NET MVC 5. In your Visual Studio go to the Package Manager Console and type:
PM> update-package
You migh get an error in the:
public ApplicationDbContext()
            : base("DefaultConnection")
        {
        }
That error is caused by the update in the internal structure of MVC 5. To solve that error do this:http://stackoverflow.com/a/23090099/2958543

1 nhận xét:

  1. i am using vs12 with mvc4 , there is an issue when using system.web.mvc.compare not found

    Trả lờiXóa