How to generate Captcha with Refresh button and validation in Asp.Net

Description:-

Captcha generation we did before in many post here I have another to do it in dot net so let’s start. Before we will see how to do it and how to validate in dot net with Validation controls. Here we can re generate Captcha also in our web page so we can fill another code in validation or any other work. Compare validation control I have used for match password and code for generate captcha and generate captcha image.

Html Code:-

<div>
   <asp:ScriptManager ID="SM1" runat="server"></asp:ScriptManager>
   <table style="border: solid 1px black; padding: 20px; position: relative; top: 50px;" align="left">
      <tr>
         <td>Email ID : </td>
         <td>
            <asp:TextBox ID="txtEmailID" runat="server" Width="200px"></asp:TextBox>
         </td>
      </tr>
      <tr>
         <td>Password : </td>
         <td>
            <asp:TextBox ID="txtPassword" runat="server" TextMode="Password" Width="200px"></asp:TextBox>
         </td>
      </tr>
      <tr>
         <td>Confirm Password : </td>
         <td>
            <asp:TextBox ID="txtConfirmPassword" runat="server" TextMode="Password" Width="200px"></asp:TextBox>
            <asp:CompareValidator ID="CompareValidator1" runat="server"
               ErrorMessage="Not Match" ControlToCompare="txtPassword"
               ControlToValidate="txtConfirmPassword" ForeColor="#CC0000"></asp:CompareValidator>
         </td>
      </tr>
      <tr>
         <td>Enter Below Code : </td>
         <td>
            <asp:TextBox ID="txtCaptcha" runat="server" Width="200px"></asp:TextBox>
         </td>
      </tr>
      <tr>
         <td></td>
         <td valign="middle">
            <asp:UpdatePanel ID="UP1" runat="server">
               <ContentTemplate>
                  <table>
                     <tr>
                        <td style="height: 50px; width: 100px;">
                           <asp:Image ID="imgCaptcha" runat="server" />
                        </td>
                        <td valign="middle">
                           <asp:Button ID="btnRefresh" runat="server" Text="Refresh" OnClick="btnRefresh_Click" />
                        </td>
                     </tr>
                  </table>
               </ContentTemplate>
            </asp:UpdatePanel>
         </td>
      </tr>
      <tr>
         <td colspan="2" align="justify">
            <asp:Label ID="lblerror" runat="server" Text=""></asp:Label>
         </td>
      </tr>
      <tr>
         <td colspan="2" align="center">
            <asp:Button ID="btnRegiser" runat="server" Text="Register" OnClick="btnRegister_Click" />
         </td>
      </tr>
   </table>
</div>

Code Behind:-

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        FillCapctha();
    }
}

void FillCapctha()
{
    try
    {
        Random random = new Random();
        string combination = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
        StringBuilder captcha = new StringBuilder();
        for (int i = 0; i < 6; i++)
        captcha.Append(combination[random.Next(combination.Length)]);
        Session["captcha"] = captcha.ToString();
        imgCaptcha.ImageUrl = "GenerateCaptcha.aspx?" + DateTime.Now.Ticks.ToString();
    }
    catch
    {
        throw;
    }
}

protected void btnRefresh_Click(object sender, EventArgs e)
{
    FillCapctha();
    lblerror.Text = string.Empty;
}

protected void btnRegister_Click(object sender, EventArgs e)
{
    if (Session["captcha"].ToString() != txtCaptcha.Text)
    {
        lblerror.ForeColor = System.Drawing.Color.Red;
        lblerror.Text = "Invalid Captcha Code";
    }
    else
    {
        lblerror.ForeColor = System.Drawing.Color.Green;
        lblerror.Text = "Valid Captcha Code";
    }
    FillCapctha();
}

Web.config file:-

<appSettings>
   <add key="ChartImageHandler" value="storage=file;timeout=20;dir=c:\TempImageFiles\;"/>
</appSettings>
<httpHandlers>
   <add path="ChartImg.axd" verb="GET,HEAD,POST" type="System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="false"/>
</httpHandlers>
<system.webServer>
   <validation validateIntegratedModeConfiguration="false"/>
   <handlers>
      <remove name="ChartImageHandler"/>
      <add name="ChartImageHandler" preCondition="integratedMode" verb="GET,HEAD,POST" path="ChartImg.axd" type="System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
   </handlers>
</system.webServer>

Now run your Webpage you we get captcha as well as compare validation in password or confirm password. Also you can refresh captcha.

Related Posts

Previous
Next Post »

Thanks for comments.....