ASP.NET prevent the bots from submitting your forms in Visual Basic
I’d had a few sites over a few years with no problems.
Then one day I got an email from my contact page, something to the effect of “cool site I like it”.
I felt pretty good about it then got another about an hour later, from another user.
Then another and another, then some gibberish ones; by the next day when my mail box was filling up, I could tell I had a problem.
After a few days I was receiving one ever ½ hour and knew I had to do something.
So, I came up with this.
I use this on my contact page.
Here is the server side code.
'GENERATE RANDOM NUMBERS IN THE PAGE LOAD
'DISPLAY THEM ON THE PAGE AND
'STORE THEM IN HIDEN FIELDS
Protected Sub Page_LoadComplete(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.LoadComplete
'RANDOMLY GENERATE THE BOT PREVENTION VALUES
Dim randObj As New Random
Dim addend1 As String = randObj.Next(1, 6).ToString()
Dim addend2 As String = randObj.Next(1, 6).ToString()
'DISPLAY THEM TO THE USER
litAddend1.Text = addend1
litAddend2.Text = addend2
'STORE THE VALUES IN HIDDEN FIELDS
hidAddend1.Value = addend1
hidAddend2.Value = addend2
End Sub
'CHECK THE BOT PREVENTION EQUATION IN THE BUTTON CLICK EVENT
'CHECK THAT THE SUM IS THE TOTAL OF THE 2 GENERATED ADDENDS
'GET THE ENTERED SUM
Dim sum As String = CInt(txtSum.Text)
If Not CInt(hidAddend1.Value) + CInt(hidAddend2.Value) = sum Then
'INCORRECT SUM DISPLAY A MESSAGE TO THE USER AND EXIT
litIncorectSum.Text = "<font class='Your error text class'>* Incorrect, please try again.</font>"
Exit Sub
End If
Here is the code I use on the .aspx page.
<!--PAGE DISPLAY WITH EQUATION AND TEXTBOX-->
Real person check, enter:
<asp:Literal runat="server" ID="litAddend1" />
+
<asp:Literal runat="server" ID="litAddend2" />
=
<asp:TextBox runat="server" ID="txtSum" Width="20" MaxLength="2" />
<!--DISPLAY FOR A MESSAGE IF THE SUM IS NOT CORRECT-->
<asp:Literal runat="server" ID="litIncorectSum" />
<!--STORE THE RANDOMLY GENERATED ADDDENDS-->
<asp:HiddenField runat="server" ID="hidAddend1" /><asp:HiddenField runat="server" ID="hidAddend2" />
Here is the onpage validation to prevent errors.
<!--SUM IS REQUIRED-->
<asp:RequiredFieldValidator ID="rfvBotSum" runat="server"
ErrorMessage="Please add up the values so I know your a real person."
Display="None" ControlToValidate="txtSum" SetFocusOnError="true" />
<!--ENTRY MUST BE A NUMBER-->
<asp:RegularExpressionValidator ID="revSum" runat="server"
ErrorMessage="Sum must be a number."
Display="None" ControlToValidate="txtSum" SetFocusOnError="true" ValidationExpression="[0-9]" />
<!--ALERT THE USER THERE IS A PROBLEM -->
<asp:ValidationSummary ID="ValidationSummary" runat="server" DisplayMode="BulletList"
HeaderText="Cannot submit the form!" ShowMessageBox="true" ShowSummary="true" />