Click here to Skip to main content
Click here to Skip to main content

ASP.NET Validation Control for User Registration

, 26 Feb 2013 CPOL
Rate this:
Please Sign up or sign in to vote.
ASP.NET validation control for user registration

Introduction

Here I will give you a Validation expression that will be very useful to implement in Registration Forms.

Background

For validating the user details, we use some JavaScript function. To overcome that, we may use the validation controls in ASP.NET but even that is complicated for certain controls.

Using the Code

To avoid those complications, I use regular expressions to validate user input. Here, I am using the following code to validate the user credentials during registration.

Default.aspx

 <%@ Page Language="C#" AutoEventWireup="true"  
CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="
AjaxControlToolkit" TagPrefix="asp" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Registration Page</title>
    <link rel=Stylesheet type="text/css" href=style.css />
    <script type="text/javascript">

function isNumberKey(evt)
{
 var charCode = (evt.which) ? evt.which : event.keyCode
 if (charCode > 31 && (charCode < 48 || charCode > 57) )
    return false;


 return true;
}
<pre lang="C++"></script> <span style="
font-size: 9pt;"></head></span> <span style="
font-size: 9pt;">    </span>
<body>
<center>
    &nbsp;
    Registration Form<br /></center>
    <form id="form1" runat="server">
    <div style="text-align: center">
        
        &nbsp;<table style="width: 555px; text-align: right;">
            <tr>
                <td id="UserIDLabel" style="width: 2401px; 
                text-align: left; height: 34px;">
                    User Name</td>
                <td style="width: 1166px; height: 34px; 
                text-align: left;">
                    <asp:TextBox ID="txt_UserName" runat="
                    server"></asp:TextBox></td>
                <td style="width: 1702px; text-align: left; height: 34px;">
                    <asp:RequiredFieldValidator ID="UserNameRequired" 
                    runat="server" ControlToValidate="txt_UserName"
                        ErrorMessage="Enter UserName" 
                        ValidationGroup="val1" SetFocusOnError="True">
                        </asp:RequiredFieldValidator>
                </td>
            </tr>
            <tr>
                <td id="PasswordLabel" style="
                width: 2401px; text-align: left; height: 31px;">
                    Password</td>
                <td style="width: 1166px; height: 31px; text-align: left;">
                    <asp:TextBox ID="txt_Password" 
                    runat="server" MaxLength="10" 
                    Width="111px" TextMode="Password" >
                    </asp:TextBox></td>
                <td style="width: 1702px; text-align: left; height: 31px;">
                    <asp:RequiredFieldValidator ID="PasswordRequired" 
                    runat="server" ControlToValidate="txt_Password"
                        ErrorMessage="Enter Password" 
                        ValidationGroup="val1"></asp:RequiredFieldValidator>
                    </td>
            </tr>
            <tr>
                <td id="FullNameLabel" style="width: 2401px; 
                text-align: left; height: 34px;">
                    Full Name</td>
                <td style="width: 1166px; height: 34px; text-align: left;">
                    <asp:TextBox ID="txt_FullName" 
                    runat="server"></asp:TextBox></td>
                <td style="width: 1702px; height: 34px;">
    <asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
    </asp:ToolkitScriptManager>
                </td>
            </tr>
            <tr>
                <td id="QualificationLabel" style="
                width: 2401px; text-align: left; height: 23px;">
                    Qualification</td>
                <td style="width: 1166px; height: 23px; text-align: left;">
                    <asp:DropDownList ID="Qualification_DropList" 
                    runat="server">
                        <asp:ListItem>B.E.</asp:ListItem>
                        <asp:ListItem>B.Tech</asp:ListItem>
                        <asp:ListItem>M.E.</asp:ListItem>
                        <asp:ListItem>MCA</asp:ListItem>
                        <asp:ListItem>M.Tech</asp:ListItem>
                    </asp:DropDownList>
                </td>
                <td style="width: 1702px; height: 23px;">
    <asp:CalendarExtender ID="CalendarExtender1" TargetControlID="txt_DOB" 
    Format="dd/MM/yyyy" PopupButtonID="imgCal" runat="server">
    </asp:CalendarExtender>
                </td>
            </tr>
            <tr>
                <td id="DOBLabel" style="width: 2401px; 
                text-align: left; height: 26px;">
                    Date of Birth</td>
                <td style="width: 1166px; height: 26px; text-align: left;">
                    <asp:TextBox ID="txt_DOB" runat="server" 
                    MaxLength="10" Width="111px" ></asp:TextBox>
                    <asp:ImageButton ID="imgCal" runat="server" 
                    ImageUrl="cal.png" Height="21px" Width="23px" />
                    </td>
                <td style="width: 1702px; text-align: left; height: 26px;">
                    <asp:RequiredFieldValidator ID="DOBRequired" 
                    runat="server" ControlToValidate="txt_DOB"
                        ErrorMessage="Enter Date Of Birth" 
                        ValidationGroup="val1" Width="118px">
                        </asp:RequiredFieldValidator>
                        <asp:CustomValidator ID="DateValidator" runat="server" 
                        ControlToValidate="txt_DOB" 
                        ErrorMessage="Date Must be in the Format(DD/MM/YYYY)" 
                        ValidationGroup="val1" Width="281px" 
                        Height="3px"></asp:CustomValidator></td>
            </tr>
            <tr>
                <td id="EmailIDLabel" style="width: 2401px; text-align: left; height: 32px;">
                    Email ID</td>
                <td style="width: 1166px; height: 32px; text-align: left;">
                    <asp:TextBox ID="txt_EmailID" 
                    runat="server"></asp:TextBox></td>
                <td style="width: 1702px; text-align: left; height: 32px;">
                    <asp:RequiredFieldValidator ID="EmailIDRequired" 
                    runat="server" ControlToValidate="txt_EmailID"
                        ErrorMessage="Enter Email ID" 
                        ValidationGroup="val1"></asp:RequiredFieldValidator>
                    <asp:RegularExpressionValidator ID="EmailIDValidation" 
                    runat="server" ControlToValidate="txt_EmailID"
                        ErrorMessage="Enter Email ID Properly" 
                        ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"
                        ValidationGroup="val1"></asp:RegularExpressionValidator></td>
            </tr>
            <tr>
                <td id="mNoLabel" style="width: 2401px; text-align: left">
                    Mobile No</td>
                <td style="width: 1166px; text-align: left;">
                    <asp:TextBox ID="TextBox1" runat="server" 
                    Enabled="False" Width="21px">+91</asp:TextBox>
                    <asp:TextBox ID="txt_mNo" CssClass="textbox" 
                    runat="server" MaxLength="10" 
                    Width="73px"></asp:TextBox></td>
                <td style="width: 1702px; text-align: left;">
                    <asp:RequiredFieldValidator ID="mNORequired" 
                    runat="server" ControlToValidate="txt_mNo"
                        ErrorMessage="Enter Mobile Number" 
                        ValidationGroup="val1"></asp:RequiredFieldValidator>
                    <asp:RegularExpressionValidator ID="mNoValidator" 
                    runat="server" ControlToValidate="txt_mNo"
                        ErrorMessage="Mobile Number must be 10 digits(Numerals)" 
                        ValidationExpression="\d+">
                        </asp:RegularExpressionValidator></td>
            </tr>
            <tr>
                <td style="width: 2401px; text-align: left; height: 59px;">
                </td>
                <td style="width: 1166px; height: 59px;">
                    <asp:Button ID="Button1" runat="server" 
                    Text="Submit" ValidationGroup="val1" 
                    OnClick="Button1_Click"  /></td>
                <td style="width: 1702px; height: 59px;">
                    <asp:RegularExpressionValidator ID="PasswordValidator" 
                    runat="server" ControlToValidate="txt_Password"
                        ErrorMessage="Password must be 8 to 10 Characters and must 
                        contain a Capital and small alphabet with numerals and special Characters" 
                        ValidationExpression="^.*(?=.{8,10})(?=.*[\d])(?=
                        .*[\W])(?=.*[a-z])(?=.*[A-Z]).*$"></asp:RegularExpressionValidator></td>
            </tr>
        </table>
        &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 
        &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 
        &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
        &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 
        &nbsp; &nbsp; &nbsp;<br />
    
    </div>
    </form>
</body>
</html>  
<?xml version="1.0"?>
<configuration>
  <configSections>
    <sectionGroup name="system.web.extensions" type="
    System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, 
    Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
      <sectionGroup name="scripting" type="
      System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, 
      Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
        <section name="scriptResourceHandler" type="
        System.Web.Configuration.ScriptingScriptResourceHandlerSection, 
        System.Web.Extensions, Version=3.5.0.0, Culture=neutral, 
        PublicKeyToken=31BF3856AD364E35" requirePermission="false" 
        allowDefinition="MachineToApplication"/>
        <sectionGroup name="webServices" 
        type="System.Web.Configuration.ScriptingWebServicesSectionGroup, 
        System.Web.Extensions, Version=3.5.0.0, Culture=neutral, 
        PublicKeyToken=31BF3856AD364E35">
          <section name="jsonSerialization" 
          type="System.Web.Configuration.ScriptingJsonSerializationSection, 
          System.Web.Extensions, Version=3.5.0.0, Culture=neutral, 
          PublicKeyToken=31BF3856AD364E35" requirePermission="false" 
          allowDefinition="Everywhere"/>
          <section name="profileService" 
          type="System.Web.Configuration.ScriptingProfileServiceSection, 
          System.Web.Extensions, Version=3.5.0.0, Culture=neutral, 
          PublicKeyToken=31BF3856AD364E35" requirePermission="false" 
          allowDefinition="MachineToApplication"/>
          <section name="authenticationService" 
          type="System.Web.Configuration.ScriptingAuthenticationServiceSection, 
          System.Web.Extensions, Version=3.5.0.0, Culture=neutral, 
          PublicKeyToken=31BF3856AD364E35" requirePermission="false" 
          allowDefinition="MachineToApplication"/>
          <section name="roleService" type="
          System.Web.Configuration.ScriptingRoleServiceSection, System.Web.Extensions, 
          Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" 
          requirePermission="false" allowDefinition="MachineToApplication"/>
        </sectionGroup>
      </sectionGroup>
    </sectionGroup>
  </configSections>
  <appSettings/>
  <connectionStrings>
    
  </connectionStrings>
  <system.web>
   
    <compilation debug="true">
      <assemblies>
        <add assembly="System.Core, Version=3.5.0.0, 
        Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
        <add assembly="System.Data.DataSetExtensions, Version=3.5.0.0, 
        Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
        <add assembly="System.Web.Extensions, Version=3.5.0.0, 
        Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
        <add assembly="System.Xml.Linq, Version=3.5.0.0, 
        Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
        <add assembly="System.Design, Version=2.0.0.0, 
        Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
        <add assembly="System.Web.Extensions.Design, Version=3.5.0.0, 
        Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
        <add assembly="System.Windows.Forms, Version=2.0.0.0, 
        Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
      </assemblies>
    </compilation>
  
    <authentication mode="Windows"/>
   
    <pages>
      <controls>
        <add tagPrefix="asp" namespace="System.Web.UI" 
        assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, 
        PublicKeyToken=31BF3856AD364E35"/>
        <add tagPrefix="asp" namespace="System.Web.UI.WebControls" 
        assembly="System.Web.Extensions, Version=3.5.0.0, 
        Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
      </controls>
    </pages>
    <httpHandlers>
      <remove verb="*" path="*.asmx"/>
      <add verb="*" path="*.asmx" validate="false" 
      type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, 
      Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
      <add verb="*" path="*_AppService.axd" validate="false" 
      type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, 
      Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
      <add verb="GET,HEAD" path="ScriptResource.axd" 
      type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, 
      Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" validate="false"/>
    </httpHandlers>
    <httpModules>
      <add name="ScriptModule" type="System.Web.Handlers.ScriptModule, 
      System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
    </httpModules>
  </system.web>
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" 
      warningLevel="4" type="Microsoft.CSharp.CSharpCodeProvider, 
      System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
        <providerOption name="CompilerVersion" value="v3.5"/>
        <providerOption name="WarnAsError" value="false"/>
      </compiler>
    </compilers>
  </system.codedom>
 
  <system.webServer>
    <validation validateIntegratedModeConfiguration="false"/>
    <modules>
      <remove name="ScriptModule"/>
      <add name="ScriptModule" preCondition="managedHandler" 
      type="System.Web.Handlers.ScriptModule, System.Web.Extensions, 
      Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
    </modules>
    <handlers>
      <remove name="WebServiceHandlerFactory-Integrated"/>
      <remove name="ScriptHandlerFactory"/>
      <remove name="ScriptHandlerFactoryAppServices"/>
      <remove name="ScriptResource"/>
      <add name="ScriptHandlerFactory" verb="*" 
      path="*.asmx" preCondition="integratedMode" 
      type="System.Web.Script.Services.ScriptHandlerFactory, 
      System.Web.Extensions, Version=3.5.0.0, Culture=neutral, 
      PublicKeyToken=31BF3856AD364E35"/>
      <add name="ScriptHandlerFactoryAppServices" 
      verb="*" path="*_AppService.axd" 
      preCondition="integratedMode" 
      type="System.Web.Script.Services.ScriptHandlerFactory, 
      System.Web.Extensions, Version=3.5.0.0, Culture=neutral, 
      PublicKeyToken=31BF3856AD364E35"/>
      <add name="ScriptResource" preCondition="integratedMode" 
      verb="GET,HEAD" path="ScriptResource.axd" 
      type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, 
      Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
    </handlers>
  </system.webServer>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Extensions" 
        publicKeyToken="31bf3856ad364e35"/>
        <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" 
        newVersion="3.5.0.0"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Extensions.Design" 
        publicKeyToken="31bf3856ad364e35"/>
        <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" 
        newVersion="3.5.0.0"/>
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>
 protected void Page_Load(object sender, EventArgs e)
    {

        txt_mNo.Attributes.Add("onkeypress", "return isNumberKey(event)");
    }
   
    protected void Button1_Click(object sender, EventArgs e)
    {
        Connection.Open();
       
        Command=new SqlCommand("Select DOB,EmailId,MobileNo from 
        UserDetails where EmailId='" + txt_EmailID.Text + "' 
        and MobileNo='"+txt_mNo.Text+"' ", Connection);
        Reader=Command.ExecuteReader();
        try
        {
            if (Reader.Read())
            {
                mailid = Reader["EmailId"].ToString();
                mobileNo = Reader["MobileNo"].ToString();
           
            }
          
        }catch { }
           
            Reader.Close();
            try
            {
                if (txt_EmailID.Text.Equals(mailid) && txt_mNo.Text.Equals(mobileNo))
                {
                    MessageBox.Show("User with Same Mobile Number,
                    Date of Birth and EmailId already Exists");
                    txt_EmailID.Text = "";
                    txt_mNo.Text = "";
                    txt_DOB.Focus();
                }

                else
                {                    
                        try
                        {
                            Command = new SqlCommand("Insert into UserDetails
                            (UserId,Password,FullName,Qualification,DOB,EmailId,MobileNo) 
                            values ('" + txt_UserName.Text + "','" + 
                            txt_Password.Text + "','" + txt_FullName.Text + "',
                            '" + Qualification_DropList.SelectedValue + "','" + 
                            txt_DOB.Text + "','" + txt_EmailID.Text + "','" + 
                            txt_mNo.Text + "')", Connection);
                            Command.ExecuteNonQuery();
                            Connection.Close();
                            MessageBox.Show(txt_UserName.Text + " added successfully");
                            Response.Redirect("Default2.aspx");
                        }
                        catch (System.Data.SqlClient.SqlException ex)
                        {
                            string msg = "Insert Error:";
                            msg += ex.Message;
                        }                  
                }
            }
            catch
            {
            }
    }       

Using this code, we can implement the following validations:

  1. UserName: It must be characters of a certain length.
  2. Password: It must be a certain length and it must contain an Upper case character, a lower case character, an integer and a special character.
  3. Phone Numbers: For phone numbers, it won't allow any alphabet or special characters to enter on the textbox, whereas it accepts only integers.
  4. Mail Id: It uses Normal mailid validation.
  5. Selecting date of birth: Selecting date of birth, it is a tough task in ASP.NET, so I am using AJAX calendar control in this application.

Note: You may download the Ajax DLL from this link.

Hope you will find this useful.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Manikandan Sekar
Software Developer (Junior)
India India
No Biography provided

Comments and Discussions

 
GeneralMy vote of 1 PingroupAnand1234 201025-Apr-14 1:41 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.141223.1 | Last Updated 26 Feb 2013
Article Copyright 2013 by Manikandan Sekar
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid