ASP.NET Webform User Registration With Captcha

Introduction

In this article, you will be shown how to create an ASP.net webforms user registration form with Captcha capability. This is useful in preventing spam registrations and SQL injection.

The form will also have other validation techniques for email etc.

What is Captcha

This stands for the Completely Automated Public Turing test to tell Computers and Humans apart. There are various types like image recognition, character input, etc. This article is with regards to the character input type, i.e the software will be generating random characters as captcha.

Step 1 - Creation of Captcha.cs

 Here we will create the code to generate the captcha in C#, we have to import the necessary namespaces first, after which we will proceed with the code block to generate the captcha.

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace CaptchaDemo {
    public partial class Captcha: System.Web.UI.Page {
        protected void Page_Load(object sender, EventArgs e) {
            Bitmap objBitmap = new Bitmap(130, 80);
            Graphics objGraphics = Graphics.FromImage(objBitmap);
            objGraphics.Clear(Color.White);
            Random objRandom = new Random();
            objGraphics.DrawLine(Pens.Black, objRandom.Next(0, 50), objRandom.Next(10, 30), objRandom.Next(0, 200), objRandom.Next(0, 50));
            objGraphics.DrawRectangle(Pens.Blue, objRandom.Next(0, 20), objRandom.Next(0, 20), objRandom.Next(50, 80), objRandom.Next(0, 20));
            objGraphics.DrawLine(Pens.Blue, objRandom.Next(0, 20), objRandom.Next(10, 50), objRandom.Next(100, 200), objRandom.Next(0, 80));
            Brush objBrush =
                default (Brush);
            //create background style
            HatchStyle[] aHatchStyles = new HatchStyle[] {
                HatchStyle.BackwardDiagonal, HatchStyle.Cross, HatchStyle.DashedDownwardDiagonal, HatchStyle.DashedHorizontal, HatchStyle.DashedUpwardDiagonal, HatchStyle.DashedVertical,
                    HatchStyle.DiagonalBrick, HatchStyle.DiagonalCross, HatchStyle.Divot, HatchStyle.DottedDiamond, HatchStyle.DottedGrid, HatchStyle.ForwardDiagonal, HatchStyle.Horizontal,
                    HatchStyle.HorizontalBrick, HatchStyle.LargeCheckerBoard, HatchStyle.LargeConfetti, HatchStyle.LargeGrid, HatchStyle.LightDownwardDiagonal, HatchStyle.LightHorizontal
            };
            //create a rectangular area
            RectangleF oRectangleF = new RectangleF(0, 0, 300, 300);
            objBrush = new HatchBrush(aHatchStyles[objRandom.Next(aHatchStyles.Length - 3)], Color.FromArgb((objRandom.Next(100, 255)), (objRandom.Next(100, 255)), (objRandom.Next(100, 255))), Color.White);
            objGraphics.FillRectangle(objBrush, oRectangleF);
            //Generate the image for captcha
            string captchaText = string.Format("{0:X}", objRandom.Next(1000000, 9999999));
            //add the captcha value in session
            Session["CaptchaVerify"] = captchaText.ToLower();
            Font objFont = new Font("Courier New", 15, FontStyle.Bold);
            //Draw the image for captcha
            objGraphics.DrawString(captchaText, objFont, Brushes.Black, 20, 20);
            objBitmap.Save(Response.OutputStream, ImageFormat.Gif);
        }
    }
}

Step 2 - Creation of Captcha.aspx

This is the Aspx page that will house the cs code above.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Captcha.aspx.cs" Inherits="CaptchaDemo.Captcha" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    </div>
    </form>
</body>
</html>

Step 3 - Creation of Registration.aspx

This is the Aspx page that users will register from, it will include text boxes for email, password, password confirmation, captcha input, and user name.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Registration.aspx.cs" Inherits="Asp_Registration_Form.Registration" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Registration form with captcha by Sola Oshinowo</title>

    <link href="Style.css" rel="stylesheet" />

     <style>
        @import url('https://fonts.googleapis.com/css?family=Bitter|Crete+Round|Pacifico');
         .auto-style1 {
             margin-left: 75px;
         }
         .auto-style2 {
             width: 100%;
         }
         .auto-style4 {
             width: 267px;
         }
         .auto-style5 {
             width: 440px;
         }
    </style>

</head>
<body>
  <form id="form1" runat="server">
    <section>
      <div class="container">
        <div class="inner1">
          <table class="auto-style2">
            <tr>
              <td class="auto-style5">&nbsp;</td>
              <td class="auto-style4">Sign up</td>
              <td>&nbsp;</td>
            </tr>
            <tr>
              <td class="auto-style5">&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;&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;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; User Name</td>
              <td class="auto-style4">
                <asp:TextBox ID="txturname" placeholder="Username" runat="server" Height="16px" Width="249px"></asp:TextBox>
              </td>
              <td>
                <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" Font-Size="Small" ForeColor="Red" Display="Dynamic" ControlToValidate="txturname" ErrorMessage="Please Enter Username...!"></asp:RequiredFieldValidator>
              </td>
            </tr>
            <tr>
              <td class="auto-style5">&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;&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;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; E-Mail</td>
              <td class="auto-style4">
                <asp:TextBox ID="txtemail" placeholder="E-mail" runat="server" AutoPostBack="True" Height="18px" Width="249px"></asp:TextBox>
              </td>
              <td>
                <asp:RequiredFieldValidator ID="RequiredFieldValidator2" Font-Size="Small" ForeColor="Red" Display="Dynamic" ControlToValidate="txtemail" runat="server" ErrorMessage="Please Enter Email...!"></asp:RequiredFieldValidator>
                <asp:RegularExpressionValidator ID="RegularExpressionValidator2" runat="server" ControlToValidate="txtemail" CssClass="auto-style1" ErrorMessage="Invalid email address entered." Font-Size="Small" ForeColor="Red" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator>
              </td>
            </tr>
            <tr>
              <td class="auto-style5">&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;&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;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Password</td>
              <td class="auto-style4">
                <asp:TextBox ID="txtpasswd" placeholder="Password" TextMode="Password" runat="server" Height="16px" Width="248px"></asp:TextBox>
              </td>
              <td>
                <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="txtpasswd" Font-Size="Small" ForeColor="Red" Display="Dynamic" ErrorMessage="Please Enter Password...!"></asp:RequiredFieldValidator>
              </td>
            </tr>
            <tr>
              <td class="auto-style5">&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;&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;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Password Confirm</td>
              <td class="auto-style4">
                <asp:TextBox ID="txtcops" placeholder="Retype Password" TextMode="Password" runat="server" Height="17px" Width="248px"></asp:TextBox>
              </td>
              <td>
                <asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ControlToValidate="txtcops" Font-Size="Small" ForeColor="Red" Display="Dynamic" ErrorMessage="Please Enter Confirm Password...!"></asp:RequiredFieldValidator>
                <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="txtpasswd" ErrorMessage="Password Must be 3 to 10 Characters" Display="Dynamic" Font-Size="Small" ForeColor="Red" ValidationExpression="^[a-zA-Z0-9'@&#.\s]{3,10}$"></asp:RegularExpressionValidator>
                <asp:CompareValidator ID="CompareValidator1" runat="server" ControlToCompare="txtpasswd" ControlToValidate="txtcops" ErrorMessage="Confirm Password entered is different from password, please re-enter" Font-Size="Small" ForeColor="Red"></asp:CompareValidator>
              </td>
            </tr>
            <tr>
              <td class="auto-style5">&nbsp;</td>
              <td class="auto-style4">
                <asp:Image ID="Image2" runat="server" Height="55px" ImageUrl="~/Captcha.aspx" Width="186px" />
              </td>
              <td>&nbsp;</td>
            </tr>
            <tr>
              <td class="auto-style5">&nbsp;</td>
              <td class="auto-style4">
                <asp:Label runat="server" ID="lblCaptchaMessage" Font-Size="Small"></asp:Label>
              </td>
              <td>&nbsp;</td>
            </tr>
            <tr>
              <td class="auto-style5">&nbsp;</td>
              <td class="auto-style4">
                <asp:TextBox runat="server" ID="txtVerificationCode" placeholder="Enter captcha above"></asp:TextBox>
              </td>
              <td>&nbsp;</td>
            </tr>
            <tr>
              <td class="auto-style5">&nbsp;</td>
              <td class="auto-style4">
                <asp:Button ID="Button1" OnClick="Button1_Click" runat="server" CssClass="btn" Text="Sign Me Up" />
              </td>
              <td>&nbsp;</td>
            </tr>
            <tr>
              <td class="auto-style5">&nbsp;</td>
              <td class="auto-style4">
                <asp:Label ID="Label1" Visible="false" runat="server" Text="You are Successfully Registered...!"></asp:Label>
              </td>
              <td>&nbsp;</td>
            </tr>
            <tr>
              <td class="auto-style5">&nbsp;</td>
            </tr>
          </table>
        </div>
        <div class="inner2">
          <h4>&nbsp;</h4>
          <br />
          <br />
          <br />
          <br />
        </div>
      </div>
    </section>
  </form>
 </body>
</html>

Step 4 - Creation of Registration.cs

This is the C# code page that will have the code to test that the correct captcha has been entered, and redirect to a login page, once the registration is successful. We will import the necessary namespaces first, before putting the code under the signup button on click event.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
namespace Asp_Registration_Form {
    public partial class Registration: System.Web.UI.Page {
        protected void Page_Load(object sender, EventArgs e) {}
        protected void Button1_Click(object sender, EventArgs e) {
            if (txtVerificationCode.Text.ToLower() == Session["CaptchaVerify"].ToString()) {
                Response.Redirect("Login.aspx");
            } else {
                lblCaptchaMessage.Text = "Please enter correct captcha !";
                lblCaptchaMessage.ForeColor = System.Drawing.Color.Red;
            }
        }
    }
}

Step 5 - Creation of Login.aspx page

This is just a page that the user will be redirected to, once registration is successful, you can change yours in the registration.cs above to redirect to any other page in your application.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Login.aspx.cs" Inherits="Asp_Registration_Form.Login" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Registration form with captcha by Sola Oshinowo</title>
    <link href="Style.css" rel="stylesheet" />
     <style>
        @import url('https://fonts.googleapis.com/css?family=Bitter|Crete+Round|Pacifico');
         .auto-style1 {
             margin-left: 75px;
         }
         .auto-style2 {
             width: 100%;
         }
         .auto-style3 {
             width: 439px;
         }
    </style>
</head>
 <body>
  <form id="form1" runat="server">
    <section>
      <div class="container">
        <div class="inner1">
          <table class="auto-style2">
            <tr>
              <td class="auto-style3">&nbsp;</td>
              <td>Login</td>
            </tr>
            <tr>
              <td class="auto-style3">&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;&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;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; E-Mail </td>
              <td>
                <asp:TextBox ID="txtemail" placeholder="E-mail" AutoPostBack="true" runat="server" Height="16px" Width="173px"></asp:TextBox>
              </td>
            </tr>
            <tr>
              <td class="auto-style3">&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;&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;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Password</td>
              <td>
                <asp:TextBox ID="txtpasswd" placeholder="Password" TextMode="Password" runat="server" Height="18px" Width="171px"></asp:TextBox>
              </td>
            </tr>
            <tr>
              <td class="auto-style3">&nbsp;</td>
              <td>
                <asp:Button ID="Button1" runat="server" CssClass="btn" Text="Login" />
              </td>
            </tr>
            <tr>
              <td class="auto-style3">&nbsp;</td>
              <td>&nbsp;</td>
            </tr>
          </table>
        </div>
        <div class="inner2">
          <h4>&nbsp;</h4>
          <br />
          <asp:RequiredFieldValidator ID="RequiredFieldValidator2" Font-Size="Small" ForeColor="Red" Display="Dynamic" ControlToValidate="txtemail" runat="server" ErrorMessage="Please Enter Email...!"></asp:RequiredFieldValidator>
          <asp:RegularExpressionValidator ID="RegularExpressionValidator2" runat="server" ControlToValidate="txtemail" CssClass="auto-style1" ErrorMessage="Invalid email address entered." Font-Size="Small" ForeColor="Red" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator>
          <br />
          <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="txtpasswd" ErrorMessage="Password Must be 3 to 10 Characters" Display="Dynamic" Font-Size="Small" ForeColor="Red" ValidationExpression="^[a-zA-Z0-9'@&#.\s]{3,10}$"></asp:RegularExpressionValidator>
          <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="txtpasswd" Font-Size="Small" ForeColor="Red" Display="Dynamic" ErrorMessage="Please Enter Password...!"></asp:RequiredFieldValidator>
          <br />
          <br />
          <br />
          <br />
          <br />
          <br />
          <br />
          <asp:Label ID="Label1" Visible="false" runat="server" Text="You are Successfully Registered...!"></asp:Label>
        </div>
      </div>
    </section>
  </form>
 </body>
</html>

Final Outcome

Below are images of the outcome with various validation being tested.

Final Outcome

Final Outcome

Final Outcome

Final Outcome

Conclusion

If you download the zip folder in this article, ensure you read the instructions.txt file first.  Thank you