The Compare
attribute compares two properties of a model.
The error message can be specified using property ErrorMessage
, or using resource files.
To use Compare
attribute include using
for the following namespace:
using System.ComponentModel.DataAnnotations;
Then you can use the attribute in your model:
public class RegisterModel
{
public string Email { get; set; }
[Compare("Email", ErrorMessage = "The Email and Confirm Email fields do not match.")]
public string ConfirmEmail { get; set; }
}
When this model is validates, if Email
and ConfirmEmail
have different values, validation will fail.
Localized error messages
Just like with all validation attributes, it is possible to use error messages from resource files. In this sample the error message will be loaded from resource file Resources
, resource name is CompareValidationMessage
:
public class RegisterModel
{
public string Email { get; set; }
["Email", ErrorMessageResourceType = typeof(Resources), ErrorMessageResourceName = "CompareValidationMessage")]
public string ConfirmEmail { get; set; }
}
Avoid strings in property names
To avoid using string for property value, in C# 6+ you can use nameof
keyword:
public class RegisterModel
{
public string Email { get; set; }
[Compare(nameof(Email), ErrorMessage = "The Email and Confirm Email fields do not match.")]
public string ConfirmEmail { get; set; }
}
Placeholders in error messages
You can use placeholders in your error messages. Placeholder {0}
is replaced with the display name of current property and {1}
is replaced with display name of related property:
public class RegisterModel
{
[Display(Name = "Email")]
public string Email { get; set; }
[Display(Name = "Confirm Email")]
[Compare("Email", ErrorMessage = "The '{1}' and '{0}' fields do not match.")]
public string ConfirmEmail { get; set; }
}
If validation of the model fails, the error message will be
The 'Email' and 'Confirm Email' fields do not match.