RealMarkSussex
RealMarkSussex

Reputation: 21

How to use compare attribute to validate new password?

Here is the code:

public string NewPassword { get; set; }
public string NewPasswordConfirm { get; set; }
public string NewFirstName { get; set; }
public string NewLastName { get; set; }
public AccountSettingsViewModel()
{
    Title = "Account";
}

I'm trying to make sure that the new password and new password confirm are the same using the Compare Attribute. How would i go about doing this?

Upvotes: 1

Views: 811

Answers (2)

jenkamin-benbins
jenkamin-benbins

Reputation: 71

Your code should be something like this:

    using System.ComponentModel.DataAnnotations;
    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 NewPasswordConfirm{ get; set; }

The preceding code is using Compare DataAnnotation to compare the NewPassword to the NewPasswordConfirm.

For more visit: https://riptutorial.com/asp-net-mvc/example/19533/compare-attribute.

Upvotes: 1

Kaj
Kaj

Reputation: 246

You can use Compare DataAnnotation , and the parameter will be Password property in your model.

[Required]
public string NewPassword { get; set; }
[Compare("NewPassword")]
public string NewPasswordConfirm { get; set; }

Upvotes: 1

Related Questions