NDE Designs


Contact Forms and Spam


Contact Forms

One part of this relatively new portfolio website that I am fairly proud of is my contact form on the contact page. Why? Well, it took a fair amount of time to build as I coded it from scratch and it validates all the sections in real time using JavaScript (if the user has it enabled in their browser), but will also validate the form using PHP when the user submits it (so if a user has JavaScript disabled the form will still validate). It also means that I can now just copy and paste (most of it) into other websites that I create, and I will be able to make it better as time goes by.

It is also something I have been asked about a few times by fellow webmasters and people trying to learn so I thought it would be best to put the codes on here so people can have a look for themselves.

Spam

One reason I decided to code in validation on all the fields was that my old contact form (a basic email form) was receiving about 3-5 spam emails a week and it was just wasting my time even looking at them.

Okay, so even now I havent completely got rid of the spam emails, but I have cut them down from about 3-5 a week to less than 1 each week so I would say it was a good success. I still wouldn’t be happy putting a form like this on a client’s website as they will likely attract more spam bots than my website does (assuming their website attracts more traffic than this portfolio site does – which is fairly little at the moment) and thus will likely receive more spam than I do at the moment. I suppose I could make it more secure by putting a captcha or something on it, but I find them annoying and wouldn’t put them into a website unless I was asked to by the client.

Ways to Combat Spam

I thought I may as well tell you the methods I have used on my contact form to combat spam (and lets hope it’ll help you make your forms more secure).

I don’t plan on going into detail about what each part of the code does, so a background knowledge of working with PHP and forms would be good to have if you want to understand the following.

Basically my form uses two validation methods – one to validate the number of characters in the field (used on the name and message fields), and one to validate the email address (used on the email address field). I do each of the validation methods twice – once as the user types using JavaScript (if the user has JS turned on) and once when the form is submitted using PHP.

The form I have used these methods on is the contact form on this site, so you can view the source there to get the HTML code for that (and I think thats the only code I have missed out below).

PHP Methods

These are the more important ones to use as they will execute even if the user turns off JavaScript in their browser. You can even leave out the JavaScript methods if you like.

Validate number of characters
<?php
function validateName($name){
if(strlen($name) < 3)
return false;
else
return true;
}
?>

and

<?php
function validateMessage($message){
if(strlen($message) < 10)
return false;
else
return true;
}
?>
Validate an email address
<?php
function validateEmail($email){
return ereg("^[a-zA-Z0-9]+[a-zA-Z0-9_-]+@[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$", $email);
}
?>

These functions I add into a file of their own and then include into the contact page (just to clean the file up a bit).

The Execution

You would want to put this on the PHP page that your contact form is on. Basically what it does is when the form is submitted it checks the post data through the functions I mentioned previously, then if the information is all valid will send the email. If the information is not valid then it will output what has to be changed to the user.

<?php if( isset($_POST['submit']) && (!validateName($_POST['name']) || !validateEmail($_POST['email']) || !validateMessage($_POST['message']) ) ) {
echo '<div id="error">
<ul>
';
if(!validateName($_POST['name'])) {
echo '<li><strong>Invalid Name</strong>: The name must contain at least 3 characters</li>
';
}
if(!validateEmail($_POST['email'])) {
echo '<li><strong>Invalid e-mail</strong>: The email must be a valid email address</li>
';
}
if(!validateMessage($_POST['message'])) {
echo '<li><strong>Invalid message:</strong> Type a message with at least with 10 letters</li>
';
}
echo '</ul>
</div>
';
} else {
if(isset($_POST['submit'])) {  // change the following to your own details
$to = "email_address_here";
$subject = "Email Title: " . $_POST['name'];
$name_field = $_POST['name'];
$email_field = $_POST['email'];
$message = $_POST['message'];
 
$body = "From: $name_field\n E-Mail: $email_field\n Message:\n $message";
 
echo "<p>Email sent successfully.<br />
Expect me to reply soon.
<br />Thank you.</p>";
mail($to, $subject, $body);
}}?>

JavaScript Methods

The Whole Shebang

Why give the whole JS code at once you ask? Well, to put it simply, it’s easier for me. Especially as everything needs to be inside the document ready function. Means I won’t have to explain where to put each bit of the code.

$(document).ready(function(){
//global vars
var form = $("#form_contact");
var name = $("#name");
var nameInfo = $("#nameInfo");
var email = $("#email");
var emailInfo = $("#emailInfo");
var message = $("#message");
 
//On blur
name.blur(validateName);
email.blur(validateEmail);
//On key press
name.keyup(validateName);
message.keyup(validateMessage);
//On Submitting
form.submit(function(){
if(validateName() & validateEmail() & validateMessage())
return true
else
return false;
});
 
//the validation functions
function validateEmail(){
//testing the regular expression for the email
var a = $("#email").val();
var filter = /^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-zA-Z0-9_-]+@[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$/;
//if it's valid email (in the form string@string.string)
if(filter.test(a)){
email.removeClass("error");
emailInfo.text("Valid e-mail please, I will need it to reply.");
emailInfo.removeClass("error");
return true;
}
//if it's NOT valid then add class and text via the DOM
else{
email.addClass("error");
emailInfo.text("Invalid e-mail: The email must be a valid email address");
emailInfo.addClass("error");
return false;
}
}
function validateName(){
//if it's NOT valid (i.e. length is less than 3 characters) then add class and text via the DOM
if(name.val().length < 3){
name.addClass("error");
nameInfo.text("Invalid Name: The name must contain at least 3 characters");
nameInfo.addClass("error");
return false;
}
//if it's valid
else{
name.removeClass("error");
nameInfo.text("What is your name?");
nameInfo.removeClass("error");
return true;
}
}
function validateMessage(){
//it's NOT valid (length less than 10 characters) then add class and text via the DOM
if(message.val().length < 10){
message.addClass("error");
return false;
}
//it's valid
else{
message.removeClass("error");
return true;
}
}
});
Validation CSS

I thought I best give you all the CSS code too (for the validation parts of the form at least) just so you have the code that you can just copy and paste (and make some changes to as you see fit).

#form_contact label{
display: block;
font-weight: 700;
line-height: 1.4em;
}
 
#form_contact input{
width: 220px;
border: 1px solid #1e1a19;
}
 
#form_contact input.error{
background: #f8dbdb;
border-color: #e77776;
}
 
#form_contact textarea{
width: 500px;
height: 150px;
color: #000000;
font-style: italic;
border: 1px solid #1e1a19;
}
 
#form_contact textarea.error{
background: #f8dbdb;
border-color: #e77776;
}
 
#form_contact span{
margin-left: 10px;
color: #b1b1b1;
font-style: italic;
}
 
#form_contact span.error{
color: #e77776;
}

Well, enjoy making your forms more secure! Also, if you can think of a way to make the validation better, or make the form more secure in another way then drop me a comment below (or use the contact form to contact me via email), I’m always interested in ways to better my own coding.

Posts You Might Also Like

Leave a Reply

Comment Live Preview:

You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Powered by WP Hashcash

Nick Edwards

Web Developer


Web Designer



My Twitter

This time next week, I'll be in Dubai en route to Aus! Can't wait!


My Web Presence

My Facebook ProfileMy Linkedin Profile

My Myspace ProfileMy Twitter Profile

Subscribe to my blog feed