Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using DataAnnotations to compare two model properties

How would I go about writing a custom ValidationAttribute that compares two fields? This is the common "enter password", "confirm password" scenario. I need to be sure the two fields are equal and to keep things consistent, I want to implement the validation via DataAnnotations.

So in pseudo-code, I'm looking for a way to implement something like the following:

public class SignUpModel {     [Required]     [Display(Name = "Password")]     public string Password { get; set; }      [Required]     [Display(Name = "Re-type Password")]     [Compare(CompareField = Password, ErrorMessage = "Passwords do not match")]     public string PasswordConfirm { get; set; } }  public class CompareAttribute : ValidationAttribute {     public CompareAttribute(object propertyToCompare)     {         // ??     }      public override bool IsValid(object value)     {         // ??     } } 

So the question is, how do I code the [Compare] ValidationAttribute?

like image 225
Scott Avatar asked Feb 08 '11 20:02

Scott


People also ask

What is the use of using system ComponentModel DataAnnotations?

Data annotations (available as part of the System. ComponentModel. DataAnnotations namespace) are attributes that can be applied to classes or class members to specify the relationship between classes, describe how the data is to be displayed in the UI, and specify validation rules.

What is DataAnnotations MVC?

DataAnnotations is used to configure your model classes, which will highlight the most commonly needed configurations. DataAnnotations are also understood by a number of . NET applications, such as ASP.NET MVC, which allows these applications to leverage the same annotations for client-side validations.


1 Answers

Make sure that your project references system.web.mvc v3.xxxxx.

Then your code should be something like this:

using System.Web.Mvc; 

. . . .

[Required(ErrorMessage = "This field is required.")]     public string NewPassword { get; set; }  [Required(ErrorMessage = "This field is required.")] [Compare(nameof(NewPassword), ErrorMessage = "Passwords don't match.")] public string RepeatPassword { get; set; } 
like image 66
Janx from Venezuela Avatar answered Sep 21 '22 05:09

Janx from Venezuela