Share Blog

Friday, September 15, 2017

Custom Mathematical CAPTCHA in C# Asp.net




<form id="form1" runat="server">
    <div>
    <table cellpadding="2" cellspacing="0" border="1" style="width: 500px; border: dashed 2px #04AFEF;
            background-color: #B0E2F5">
        <tbody><tr>
            <td colspan="2">
                <h3>
                    Give your Details.</h3>
                <asp:ValidationSummary ForeColor="Red" runat="server" ValidationGroup="v" ID="ValidationSummary">
            </asp:ValidationSummary></td>
        </tr>
        <tr>
            <td >
                <b>Name</b>
            </td>
            <td >
                <asp:TextBox runat="server" id="txtName" width="60%"></asp:TextBox>
                <asp:RequiredFieldValidator id="RequiredFieldValidator1" runat="server" ErrorMessage="Please enter Your Name." ForeColor="Red" Display="Dynamic" ControlToValidate="txtName" ValidationGroup="v" >
            </asp:RequiredFieldValidator></td>
        </tr>
        <tr>
            <td>
                <b>Mobile</b>
            </td>
            <td>
                <asp:TextBox runat="server" width="60%" id="txtMobile" MaxLength="10"></asp:TextBox>
                <asp:RequiredFieldValidator id="RequiredFieldValidator2" ControlToValidate="txtMobile" runat="server" ForeColor="Red" ErrorMessage="Please Enter Your Mobile." Display="Dynamic" ValidationGroup="v" >
               </asp:RequiredFieldValidator><asp:RegularExpressionValidator ID="RegularExpressionValidator2"  ControlToValidate="txtMobile"
                                                    runat="server" ValidationGroup="v" ValidationExpression="(\d*-)?\d{10}"
                                                    Display="Dynamic"  ErrorMessage="Invalid Mobile No" ForeColor="Red"></asp:RegularExpressionValidator> </td>
        </tr>
        <tr>
            <td style="vertical-align: top;">
                <b>Description</b>
            </td>
            <td>
                <asp:TextBox runat="server" id="txtDescription" textmode="MultiLine" height="200px" width="100%"></asp:TextBox>
                 <asp:RequiredFieldValidator id="RequiredFieldValidator3" controltovalidate="txtDescription" ForeColor="Red" runat="server" ErrorMessage="Please Enter Your Description." Display="Dynamic" ValidationGroup="v" >
               </asp:RequiredFieldValidator></td>
        </tr>
        <tr>
            <td>
                <b>
                    <asp:label id="lblStopSpam" runat="server"></asp:label> = </b>
            </td>
            <td>
                <asp:TextBox runat="server" id="txtStopSpam"> </asp:TextBox>
                <asp:RequiredFieldValidator id="RequiredFieldValidator4" ForeColor="Red" ErrorMessage="Please enter your answer." Display="Dynamic" validationgroup="v" ControlToValidate="txtStopSpam" runat="server">
                </asp:RequiredFieldValidator><asp:CompareValidator id="CompareValidator1" ForeColor="Red" ErrorMessage="Invalid text format." Display="Dynamic" ValidationGroup="v" ControlToValidate="txtStopSpam" runat="server" Operator="DataTypeCheck" Type="Integer">
            </asp:CompareValidator></td>
        </tr>
        <tr>
            <td>
                 
            </td>
            <td>
                <asp:button id="btnSubmit" text="Submit" runat="server" validationgroup="v" onclick="btnSubmit_Click">
            </asp:button></td>
        </tr>
    </tbody></table>
    </div>
    </form>


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            //===== Add text to stop spammer.
            generateText();
        }
    }
    void clear()
    {
        txtName.Text = "";
        txtMobile.Text = "";
        txtDescription.Text = "";
        txtStopSpam.Text = "";
    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        if (txtStopSpam.Text == ViewState["cal"].ToString())
        {
            //---- Do your operations here.
            //--- I have shown confirmation message.
            CustomValidator val = new CustomValidator();
            val.ValidationGroup = "v";
            val.IsValid = false;
            val.ErrorMessage = "Congratulations you have successfully solved the CAPTCHA.";
            this.Page.Validators.Add(val);

            //==== Create new spam protection code.
            generateText();
            clear();
        }
        else
        {
            CustomValidator val = new CustomValidator();
            val.ValidationGroup = "v";
            val.IsValid = false;
            val.CssClass = "valFailure";
            val.ErrorMessage = "You have entered invalid captcha code. Please retry.";
            this.Page.Validators.Add(val);

            //---- Generate new captcha code.
            generateText();
        }
    }

    private void generateText()
    {
        Random ran = new Random();
        //--- Here I have used numbers between 1 to 9 you can increase as per your req.
        int firstNumber = ran.Next(1, 100);
        int secondNumber = ran.Next(1, 100);
        ViewState["cal"] = firstNumber + secondNumber;
        lblStopSpam.Text = firstNumber.ToString() + " + " + secondNumber.ToString();
    }

}