build-website-header
spacer-image
 

Contact Form Part 4 - Using JavaScript for Spam Prevention

 

If you don't have access to your form processor code then you can use JavaScript to check the form before it is submitted.

You can also use it in addition to the check in the php script ( a double check).

Here is the JavaScript code that does the check. You need to insert it at the top of your page.

You may want to consult the Adding JavaScript to Web Pages part of the JavaScript starting guide.

 

<script language="javascript">
<!--
/*Change the value to to suit your own site*/
function checkcode(myform) {

if (myform.valid.value=="1234") {

return true;
}
else {
alert("Invalid code try again")
myform.valid.focus()
myform.valid.select()
return false
}
}

//-->
</script>

The Value highlighted in blue is what the visitor must enter into the form security field. If you change this value you need to change it on the form and in the script.

The form needs to be configured to call the security check when submitted. To do this you need to modify the form tag as shown in green highlight below.

 

<form onsubmit="return checkcode(this)"   action="askwebmasterform.php" method="post">

 

Common Errors

1) The form field has the wrong name which does not match the name used in the JavaScript code. Here is the  HTML of the part of the form that accepts the security code. I have highlighted the field name in the form and JavaScript above in yellow.

 

<b><font="Verdana"><font size="2"><font color="red">For Your Security and to Stop "SpamBots", please enter the following security code (in blue) </font></font size><font color="#000080">1234 </font>
<font color="red" size="2">&nbsp;in the box below and click on "Send"</font></b></font color><br><br>
&nbsp;<p>&nbsp;Security Code:
<input id="valid" name="valid" type="text" size="20" />

 

2) You have change the security code value that they need to type but have not changed the value in the Script. (blue highlight).

3) You are not calling the script correctly. See green highlight above. The JavaScript function you are calling is called checkcode.

4) You Forgot to put the JavaScript on the page.

 

 

Google
Web www.build-your-website.co.uk


 

spacer2-image