I have seen a lot of ASP.Net examples that show you the markup required to display a page with a password and a confirm password text boxes, together with the validation controls.

The majority of the examples however only show you how to make a password mandatory and how to check that the two passwords inside the text boxes are the same. While this is all fine and works, I also want to show you how you can configure the validation controls to make the password entry optional.

The code below can be used when you want to make the password optional, so there is no RequiredFieldValidator in it. However if the user types some text in any one of the password fields, I now want to make both of the text boxes to be the same, and so now they both become mandatory. This is achieved by using two CompareValidator controls, one for each TextBox.

<asp:TextBox ID="txtAccountPassword" runat="server" TextMode="Password"> </asp:TextBox>

<asp:CompareValidator ID="cmpvldPassword" runat="server" ControlToCompare="txtAccountPasswordConfirm" ControlToValidate="txtAccountPassword" Display="Dynamic" ValidationGroup="update" ForeColor="Red" ErrorMessage="*"></asp:CompareValidator>

<asp:TextBox ID="txtAccountPasswordConfirm" runat="server" TextMode="Password"></asp:TextBox>

<asp:CompareValidator ID="cmpvldPasswordConfirm" runat="server" ControlToCompare="txtAccountPassword" ControlToValidate="txtAccountPasswordConfirm" Display="Dynamic" ValidationGroup="update" ForeColor="Red" ErrorMessage="*"></asp:CompareValidator>

One example where I have used this is when I built an application where I wanted users to configure automated tasks by using their domain accounts. The users had the option to associate tasks to run under a particular account, but it was not necessary to enter a password for an account that was already stored in the database. The password and confirm password fields were only mandatory when a new user was being entered or the password needed to be changed.


Comment by edvella on
Thanks for the comment. It's nice to see that my mumblings are of use to you.
Comment by Smithb140 on
I was very pleased to discover this website. I wanted to thank you for your time for this fantastic read!!

Add your comments