asp.net.netvalidationcomparevalidator

CompareValidator is missing values


I have two text box controls, txtPassword and txtPassword2 on a web form.

Using a CompareValidator control, both fields need to match.

txtPassword = "" 
txtPassword2 = "" 
No compare error 
txtPassword throws it's required field error

txtPassword = "1" 
txtPassword2 = "" 
No compare error

txtPassword = "" 
txtPassword2 = "1" 
Compare error 
txtPassword throws it's required field error

txtPassword = "1" 
txtPassword2 = "2" 
Compare error

Any idea why it's missing blank values for txtPassword2?

Here's the code:

<asp:TextBox ID="txtPassword" Text="" TextMode="Password" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="Required!" ControlToValidate="txtPassword"></asp:RequiredFieldValidator>

<asp:TextBox ID="txtPassword2" Text="" TextMode="Password" runat="server"></asp:TextBox>
<asp:CompareValidator ID="CompareValidator1" runat="server" ErrorMessage="Passwords do not match!" ControlToValidate="txtPassword2" ControlToCompare="txtPassword"></asp:CompareValidator>

Solution

  • You are adding asp:RequiredFieldValidator only for txtPassword, so if txtPassword2 left blank will not throw required field error. one thing you need to add is asp:RequiredFieldValidator for txtPassword2, and also you need to specify the validation group. hence the code will be like:

    <asp:TextBox ID="txtPassword" Text="" TextMode="Password" runat="server"></asp:TextBox>
    <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="Required!" ControlToValidate="txtPassword" ValidationGroup="checkNull"></asp:RequiredFieldValidator>
    
    <asp:TextBox ID="txtPassword2" Text="" TextMode="Password" runat="server"></asp:TextBox>
    
    <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="Required!" ControlToValidate="txtPassword2" ValidationGroup="checkNull"></asp:RequiredFieldValidator>
    
    <asp:CompareValidator ID="CompareValidator1" runat="server" ErrorMessage="Passwords do not match!" ControlToValidate="txtPassword2" ControlToCompare="txtPassword"></asp:CompareValidator>