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?
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.
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.
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With