Search code examples
asp.netsql-serveronblur

Validate User Information on Registration Page


I want to create a registration page for my web site.

I have three Text Boxes, one for user name, another for password and third for repeat password.

<asp:TextBox ID="UserName" runat="server"></asp:TextBox>  
<asp:TextBox ID="PassWord" runat="server"></asp:TextBox>  
<asp:TextBox ID="RE-Pass" runat="server"></asp:TextBox>

Now I want to check these three Text Box's values.

For the first Text Box, I should check it's value by connecting to a database to check it's unique. For the two other text boxes, I should check their values are the same.

I used on blur event but it is a client side (javascript) event not a server side event.

How can I check these value using on blur event or any other way?


Solution

  • Just use ASP.net validator controls.

    For the password textboxes, use the CompareValidator control.

    From MSDN:

    Compares the value entered by the user in an input control with the value entered in another input control, or with a constant value.

    You'd need something along the lines of:

    <asp:textbox ID="Textbox1" runat="server" TextMode="Password"></asp:textbox>
    <asp:textbox ID="Textbox2" runat="server" TextMode="Password"></asp:textbox>
    <asp:CompareValidator ID="CompareValidator1" runat="server" ErrorMessage="No Match." ControlToValidate="Textbox1" ControlToCompare="Textbox2"></asp:CompareValidator>
    

    For the username textbox you could use a Custom Validator control.

    You'll need something along the lines of:

    ASPX Page

    <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
    <asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="Invalid User     Name" ControlToValidate="TextBox3" 
    OnServerValidate="CustomValidator1_ServerValidate"></asp:CustomValidator>
    

    Code Behind

    protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
    {
         bool userNameIsValid = true; // Database check here.
    
         if (userNameIsValid)
             args.IsValid = true
         else  
             args.IsValid = false;
       }
    

    Here's a tutorial on MSDN which describes using this control to validate user input against a database.