tags:

views:

510

answers:

2

What's the best way to validate password and confirm password fields in a strongly-typed view?

Password Field Code:

<label for="BaseUser.PasswordHash">Password</label>
<%= Html.Password("BaseUser.PasswordHash", Model.BaseUser.PasswordHash)%>
<%= Html.ValidationMessage("BaseUser.PasswordHash", "*")%>

I don't know how to deal with confirm password field in mvc's way. Or just use javascript to validate?

+3  A: 

This kind of UI validation rule might be done in the controller (contrary to my original answer). Download the Nerddinner.com source code, look at the AccountController.Register method where the ValidateRegistration method is called to see a specific example.

There's a complete walk through of the nerddinner.com site available as a FREE PDF download at http://tinyurl.com/aspnetmvc but it doesn't go into the detail for your specific question in the walk through so just check out the source code as indicated above.

If you want to progressively enhance the user experience then you could layer the jquery validation plugin in the view to also validate client side.

Remember the danger with only performing the validation on the client via javascript is that all someone has to do is turn off javascript to avoid your business rules and bypass one layer of your "defense in depth" at stopping security attacks such XSS and Sql Injection.

Craig McKeachie
Thanks for your reply.As you can see, I use a wrap model to represent view. However, I don't know how to deal with the password validation work in my scenario. The only way I know is traverse the FormCollection List which obviously is not a best practice.
AntiGameZ
You may want to look into doing this particular validation in a custom ModelBinder if you really don't want a password confirmation property to muddy your model. But I tend to want all business/validation rules to live in Model.BaseUser or Model.User.
Craig McKeachie
A: 

I javascript is the way to go. If you want your validation routine on the server (what is it, anyways? standard mvc?) as well, then fine.

But why force a roundtrip for something as easy as "your passwords don't match". And if somebody wants to "hack" (e.g. turn off javascript) so that they can submit two passwords that don't match, then fine.

To do it on the server, you'd have two separate fields and if they don't match then you throw the error.

James S
thanks for your reply. My problem is I don't know how to verify password field value and password confirmation field value on user signup view, not user signin.
AntiGameZ