Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly implement "Confirm Password" in ASP.NET MVC 3?

There's already an answered question about the same subject but as it's from '09 I consider it outdated.

How to properly implement "Confirm Password" in ASP.NET MVC 3?

I'm seeing a lot of options on the Web, most of them using the CompareAttribute in the model like this one

The problem is that definitely ConfirmPassword shound't be in the model as it shouldn't be persisted.

As the whole unobstrusive client validation from MVC 3 rely on the model and I don't feel like putting a ConfirmPassword property on my model, what should I do?

Should I inject a custom client validation function? If so.. How?

like image 362
André Pena Avatar asked Jul 23 '11 15:07

André Pena


People also ask

What is my MVC password and confirm password?

When creating users in MVC application want users to enter strong password and re-enter password to confirm. Add DataAnnotations namespace to login class. DataAnnotations have Compare attribute. [Compare("Password", ErrorMessage = "Confirm password doesn't match, Type again !")]

How use compare validator for password in asp net?

The CompareValidator control is used to compare the value of one input control to the value of another input control or to a fixed value. If the input control is empty, no validation functions are called and validation succeeds. Use a RequiredFieldValidator control to prevent the user from skipping an input control.

What is password confirm?

Many think the confirm password field is necessary to include when creating a password. This is because a password field masks the user's input. If users mistype their password, they won't recognize it. The confirm password catches typos by prompting users to type their password twice.


1 Answers

As the whole unobstrusive client validation from MVC 3 rely on the model and I don't feel like putting a ConfirmPassword property on my model, what should I do?

A completely agree with you. That's why you should use view models. Then on your view model (a class specifically designed for the requirements of the given view) you could use the [Compare] attribute:

public class RegisterViewModel {     [Required]     public string Username { get; set; }      [Required]     public string Password { get; set; }      [Compare("Password", ErrorMessage = "Confirm password doesn't match, Type again !")]     public string ConfirmPassword { get; set; } } 

and then have your controller action take this view model

[HttpPost] public ActionResult Register(RegisterViewModel model) {     if (!ModelState.IsValid)     {         return View(model);     }      // TODO: Map the view model to a domain model and pass to a repository     // Personally I use and like AutoMapper very much (http://automapper.codeplex.com)      return RedirectToAction("Success"); } 
like image 96
Darin Dimitrov Avatar answered Oct 10 '22 00:10

Darin Dimitrov