PHP Contact Form with jQuery Validation

2009 April 9
by Raymond Selda

Hi there! You need a jQuery contact form for your website but don’t know how to create one? Please read along and maybe you’ll get lucky. A contact form is very helpful in giving your visitors a way to contact you. In this tutorial, I will help you on how to create your own jQuery contact form using PHP and JQuery.

Let’s start with the basics. We only need a single page for our contact form and this page will contain the markup, PHP to process our contact form and JQuery validating. For those who need to see a working demo of the jQuery contact form, you can check it out here.

Step One: jQuery Contact Form Markup

First, let’s create the markup for our contact form. Create a new page called contact.php (or whatever name you want as long as it has a PHP extension). Having a PHP file affords us the luxury of only having a single page to display and at the same time process our contact form. We also used a PHP constant for the action value of our contact form. That constant is the filename of the current file, relative to the document root. This is to ensure us that our form will go to the same page after sending our form.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>
	<title>PHP Contact Form with JQuery Validation</title>
	<meta http-equiv="content-type" content="text/html;charset=utf-8" />
	<meta http-equiv="Content-Style-Type" content="text/css" />

	<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>

	<style type="text/css">

	</style>
</head>

<body>
<div id="contact-wrapper">
	<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" id="contactform">
		<div>
		    <label for="name"><strong>Name:</strong></label>
			<input type="text" size="50" name="contactname" id="contactname" value="" />
		</div>

		<div>
			<label for="email"><strong>Email:</strong></label>
			<input type="text" size="50" name="email" id="email" value="" />
		</div>

		<div>
			<label for="subject"><strong>Subject:</strong></label>
			<input type="text" size="50" name="subject" id="subject" value="" />
		</div>

		<div>
			<label for="message"><strong>Message:</strong></label>
			<textarea rows="5" cols="50" name="message" id="message"></textarea>
		</div>
	    <input type="submit" value="Send Message" name="submit" />
	</form>
</div>
</body>
</html>

Step Two: Give it some style

We’re going to apply some styling to our contact form using CSS to make it more interesting. For the purposes of this tutorial we’re going to embed our CSS right inside contact.php inside the head section and in between the style tags.

body {
	font-family:Arial, Tahoma, sans-serif;
}
#contact-wrapper {
	width:430px;
	border:1px solid #e2e2e2;
	background:#f1f1f1;
	padding:20px;
}
#contact-wrapper div {
	clear:both;
	margin:1em 0;
}
#contact-wrapper label {
	display:block;
	float:none;
	font-size:16px;
	width:auto;
}
form#contactform input {
	border-color:#B7B7B7 #E8E8E8 #E8E8E8 #B7B7B7;
	border-style:solid;
	border-width:1px;
	padding:5px;
	font-size:16px;
	color:#333;
}
form#contactform textarea {
	font-family:Arial, Tahoma, Helvetica, sans-serif;
	font-size:100%;
	padding:0.6em 0.5em 0.7em;
	border-color:#B7B7B7 #E8E8E8 #E8E8E8 #B7B7B7;
	border-style:solid;
	border-width:1px;
}

If you’re following along, your contact form should look like this:
contactform screenshot

Step Three: Validate using JQuery

We already loaded JQuery in case you haven’t noticed in our initial contact form markup:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>

Loading JQuery alone only gets half of the job done. We still need a JQuery plugin called Validation to help us validate our contact form. After you’ve downloaded and extracted the plugin, look for jquery.validate.pack.js file and save it where your contact.php is saved and reference it from the file just like what you did with JQuery.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
<script src="jquery.validate.pack.js" type="text/javascript"></script>

Now we need to initialize the JQuery:Validation plugin in order to use it. Take note that #contactform is the id value of the form.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
<script src="jquery.validate.pack.js" type="text/javascript"></script>

<script type="text/javascript">
$(document).ready(function(){
	$("#contactform").validate();
});
</script>

After that, we now need to add a class attribute to our input fields. If you just need a required field you just add class=”required” to the input tag and when you need to require and validate an email so that the format is correct then you need to add class=”required email”. Here’s the updated markup for our jQuery contact form with the classes already added.

<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" id="contactform">
	<div>
	    <label for="name"><strong>Name:</strong></label>
		<input type="text" size="50" name="contactname" id="contactname" value="" class="required" />
	</div>

	<div>
		<label for="email"><strong>Email:</strong></label>
		<input type="text" size="50" name="email" id="email" value="" class="required email" />
	</div>

	<div>
		<label for="subject"><strong>Subject:</strong></label>
		<input type="text" size="50" name="subject" id="subject" value="" class="required" />
	</div>

	<div>
		<label for="message"><strong>Message:</strong></label>
		<textarea rows="5" cols="50" name="message" id="message" class="required"></textarea>
	</div>
    <input type="submit" value="Send Message" name="submit" />
</form>

Now refresh your jQuery contact page and submit the contact form without entering any data. Your contact page will catch the errors and hopefully will look like the image below. Also try entering a different format for the email field and you should see a different message. Try reading the Validation documentation for more validation options.

contact form with validation

Step Four: Submit and process the form using PHP

Now it’s time to add some PHP magic to our jQuery contact form! Place this code on the topmost section of your file (just above your DOCTYPE declaration). You might be wondering why we need to validate the inputs again even if we already validated the inputs using Javascript. The reason is that PHP will act as our second level of validation in case Javascript is turned off on the client’s machine. I highly suggest that you don’t rely on Javascript alone for validating form inputs. Aside from validating inputs, PHP will also be responsible for sending out the email in case no errors were found.

I’ve stripped down and borrowed the code below from this very helpful article. The green comments should basically explain what each code snippet is doing.

<?php
//If the form is submitted
if(isset($_POST['submit'])) {

	//Check to make sure that the name field is not empty
	if(trim($_POST['contactname']) == '') {
		$hasError = true;
	} else {
		$name = trim($_POST['contactname']);
	}

	//Check to make sure that the subject field is not empty
	if(trim($_POST['subject']) == '') {
		$hasError = true;
	} else {
		$subject = trim($_POST['subject']);
	}

	//Check to make sure sure that a valid email address is submitted
	if(trim($_POST['email']) == '')  {
		$hasError = true;
	} else if (!eregi("^[A-Z0-9._%-]+@[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['email']))) {
		$hasError = true;
	} else {
		$email = trim($_POST['email']);
	}

	//Check to make sure comments were entered
	if(trim($_POST['message']) == '') {
		$hasError = true;
	} else {
		if(function_exists('stripslashes')) {
			$comments = stripslashes(trim($_POST['message']));
		} else {
			$comments = trim($_POST['message']);
		}
	}

	//If there is no error, send the email
	if(!isset($hasError)) {
		$emailTo = 'youremail@yoursite.com'; //Put your own email address here
		$body = "Name: $name \n\nEmail: $email \n\nSubject: $subject \n\nComments:\n $comments";
		$headers = 'From: My Site <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;

		mail($emailTo, $subject, $body, $headers);
		$emailSent = true;
	}
}
?>

We’re almost finished! All we have to do is insert a little more PHP to output two kinds of messages. The first message is to notify us in case there were errors after our submission, and the other is a message to tell us that the email was already sent and no errors were found. The code for that will just sit right inside the contact-wrapper div but right before the jQuery contact form markup.

<?php if(isset($hasError)) { //If errors are found ?>
	<p class="error">Please check if you've filled all the fields with valid information. Thank you.</p>
<?php } ?>

<?php if(isset($emailSent) && $emailSent == true) { //If email is sent ?>
	<p><strong>Email Successfully Sent!</strong></p>
	<p>Thank you <strong><?php echo $name;?></strong> for using my contact form! Your email was successfully sent and I will be in touch with you soon.</p>
<?php } ?>

Finished Code

<?php
//If the form is submitted
if(isset($_POST['submit'])) {

	//Check to make sure that the name field is not empty
	if(trim($_POST['contactname']) == '') {
		$hasError = true;
	} else {
		$name = trim($_POST['contactname']);
	}

	//Check to make sure that the subject field is not empty
	if(trim($_POST['subject']) == '') {
		$hasError = true;
	} else {
		$subject = trim($_POST['subject']);
	}

	//Check to make sure sure that a valid email address is submitted
	if(trim($_POST['email']) == '')  {
		$hasError = true;
	} else if (!eregi("^[A-Z0-9._%-]+@[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['email']))) {
		$hasError = true;
	} else {
		$email = trim($_POST['email']);
	}

	//Check to make sure comments were entered
	if(trim($_POST['message']) == '') {
		$hasError = true;
	} else {
		if(function_exists('stripslashes')) {
			$comments = stripslashes(trim($_POST['message']));
		} else {
			$comments = trim($_POST['message']);
		}
	}

	//If there is no error, send the email
	if(!isset($hasError)) {
		$emailTo = 'youremail@yoursite.com'; //Put your own email address here
		$body = "Name: $name \n\nEmail: $email \n\nSubject: $subject \n\nComments:\n $comments";
		$headers = 'From: My Site <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;

		mail($emailTo, $subject, $body, $headers);
		$emailSent = true;
	}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>
	<title>PHP Contact Form with JQuery Validation</title>
	<meta http-equiv="content-type" content="text/html;charset=utf-8" />
	<meta http-equiv="Content-Style-Type" content="text/css" />

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
<script src="jquery.validate.pack.js" type="text/javascript"></script>

<script type="text/javascript">
$(document).ready(function(){
	$("#contactform").validate();
});
</script>

<style type="text/css">
body {
	font-family:Arial, Tahoma, sans-serif;
}
#contact-wrapper {
	width:430px;
	border:1px solid #e2e2e2;
	background:#f1f1f1;
	padding:20px;
}
#contact-wrapper div {
	clear:both;
	margin:1em 0;
}
#contact-wrapper label {
	display:block;
	float:none;
	font-size:16px;
	width:auto;
}
form#contactform input {
	border-color:#B7B7B7 #E8E8E8 #E8E8E8 #B7B7B7;
	border-style:solid;
	border-width:1px;
	padding:5px;
	font-size:16px;
	color:#333;
}
form#contactform textarea {
	font-family:Arial, Tahoma, Helvetica, sans-serif;
	font-size:100%;
	padding:0.6em 0.5em 0.7em;
	border-color:#B7B7B7 #E8E8E8 #E8E8E8 #B7B7B7;
	border-style:solid;
	border-width:1px;
}
</style>
</head>

<body>
	<div id="contact-wrapper">

	<?php if(isset($hasError)) { //If errors are found ?>
		<p class="error">Please check if you've filled all the fields with valid information. Thank you.</p>
	<?php } ?>

	<?php if(isset($emailSent) && $emailSent == true) { //If email is sent ?>
		<p><strong>Email Successfully Sent!</strong></p>
		<p>Thank you <strong><?php echo $name;?></strong> for using my contact form! Your email was successfully sent and I will be in touch with you soon.</p>
	<?php } ?>

	<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" id="contactform">
		<div>
		    <label for="name"><strong>Name:</strong></label>
			<input type="text" size="50" name="contactname" id="contactname" value="" class="required" />
		</div>

		<div>
			<label for="email"><strong>Email:</strong></label>
			<input type="text" size="50" name="email" id="email" value="" class="required email" />
		</div>

		<div>
			<label for="subject"><strong>Subject:</strong></label>
			<input type="text" size="50" name="subject" id="subject" value="" class="required" />
		</div>

		<div>
			<label for="message"><strong>Message:</strong></label>
			<textarea rows="5" cols="50" name="message" id="message" class="required"></textarea>
		</div>
	    <input type="submit" value="Send Message" name="submit" />
	</form>
	</div>
</body>
</html>

We are Done!

You have created a jQuery contact form using PHP and JQuery for validation all contained in a single page! All you have to do is put your email address in line 41 and off you go! Great job! I hope you will find this tutorial helpful as I’ve carefully detailed all the steps needed to create our contact form. Please tell me what you think and I would appreciate your comment. Thank you so much for reading and hope to see you again.

147 Responses leave one →
  1. November 6, 2009

    Great Tutorial!

  2. dariodn permalink
    November 7, 2009

    using gmail I cannot read the message. $Comments go in “subject” line of gmail?
    how can I resolve? tnx

  3. November 10, 2009

    Here is a question : Why do you validate in PHP while there is NO possibilites that error field can go through

    if(trim($_POST['subject']) == ”) {
    $hasError = true;
    }

    with the require, the empty field cannot be post

    Is there anything i dont understand ?

  4. November 18, 2009

    First off. Just wanted to say how much I really appreciate you sharing this. It is an amazing tutorial and was easy to follow.

    One major issue I had was that after submitting the form, the form fields were still there! I just added a simple Else statement and after submission only the response appears. I have pasted the code below. Second, I noticed that if I use test@test.com as the submitters email it will go through, but I won’t get the email (in my inbox, or in my spam). Does this deal with the validation javascript?


    <?php if(isset($emailSent) && $emailSent == true) { //If email is sent
    echo "Email Successfully Sent!
    Thank you for using my contact form! Your email was successfully sent and I will be in touch with you soon.
    ";
    }
    else{

    echo "

    Name:

    Email:

    Subject:

    Message:

    ";
    } ?>

  5. November 18, 2009

    oops, it looks like the code didn’t paste correctly. I’d appreciate it if you could fix. Thanks!

  6. November 18, 2009

    thank you so much! :)

  7. November 19, 2009

    Marc-André Méanrd, I have the same issue in sending empty fields without validate, what I did was:

    1º add new field:

    Teléfono:

    2º if the empty is empty I insert a message:
    if(trim($_POST['telefono']) == ”) {
    $telefono = ‘No se introdujo telefono.’;
    } else {
    $telefono = trim($_POST['telefono']);
    }
    3º add the new fields in the $body:
    $body = “Nombre: $name \n\nEmail: $email \n\nTelefono: $telefono \n\nDomicilio: $domicilio \n\nCodigo Postal: $codigo \n\nCiudad: $ciudad\n\nComments:\n $comments”;

    greets
    Fran

  8. jazzi permalink
    November 20, 2009

    //a question about the mail{}

    Hi great work. here is a question about //// mail($emailTo, $subject, $body, $headers);

    this mail{ } needs our host support smtp, unfortunately my host doesn’t support smtp, Can I use a third smtp service?

    if yes, how to write the php?

    thanks.
    jazzi

  9. Eva permalink
    December 8, 2009

    Hi I really like your form. I have a stupid question. I have a four page website and I would like to use the form on every page (for quotes I am a designer), is this the right type of form or is this gonna mess up my whole site?
    Thank you for your help

  10. December 8, 2009

    Actually that’s a very good question. I think you can use that form in any page and it won’t mess up anything. That would actually be a nice experiment for you. Maybe you could try putting the form on your sidebar. Try it and good luck.

  11. December 10, 2009

    Just wanted to thank you for this awesome and simple to follow tutorial. One thing I would suggest is getting a plugin so that the syntax is more understandable.

  12. Brice permalink
    December 14, 2009

    thank you for this tutorial !

  13. Paul permalink
    December 22, 2009

    The only (big) problem with this contact form is that after a successful send, if the page is refreshed it will send the same email again (and again and again…as often as you refresh the page).

    It should have a 3-5 second delay to show the success message, and then reset itself.

  14. Radhika permalink
    December 25, 2009

    Nice article but not work on IE5,IE6,IE7

  15. January 14, 2010

    So my contact.php is up on the webserver, and when I attempt to submit the form info I get this….

    Warning: mail() [function.mail]: SMTP server response: 451 See http://pobox.com/~djb/docs/smtplf.html. in D:\Hosting\5210379\html\contact.php on line 45

    I’m having trouble resolving this……help?!

  16. Eva permalink
    January 15, 2010

    Hi Raymond,

    I started working on the form. I put it on my first page. It looks great, I have done some css changes and it matches my website. On technical side – all the functions work properly, except for one important thing :-) – it does not send the email. I have tried mac mail, yahoo mail, nothing. The website is not finished yet, so I am testing the PHP page it through MAMP. Could that be the problem or what am I possibly doing wrong? Please help.

    Thank you

  17. Barry permalink
    January 22, 2010

    Great article! Just wondering… is there a way to display the thank you message using the same jQuery function without reloading the page?

  18. January 22, 2010

    Hi!
    I´ve the same problem as Eva, but on a PC.
    It doesn´t send any mail.
    What could be wrong?

    Thanks a lot, the tutorial is wonderful!!

  19. Eva permalink
    January 24, 2010

    Guille,

    You need to upload your php file to the server, than the form works perfectly. The problem with MAMP or WAMP is that it will let you test the page and the jquery functions, but the form just doesn’t send out emails from there. Maybe the “pro” version does who knows :-) .

    This is a great tutorial and so far only contact form that actually works, but this guy Raymond doesn’t seem to be answering posts anymore, so good luck!

  20. January 24, 2010

    Thanks Eva for taking the time to answer the question. I know that will help many people with their issues with the contact form. Everything is laid out in this form and I don’t plan to update it. If everything doesn’t work for the first time then don’t give up. Look at every line and test everything. Actually I didn’t get this to work the first time and it took me quite a long time to make it really work. Just don’t quit. This is only a basic form and you can take it to the next level if you want to. Honestly it’s been a while since I’ve programmed in PHP. hahaha.

  21. Eva permalink
    January 28, 2010

    Raymond lives! hahaha, what a surprise, I thought you have abandoned the page.

    Anyway, since I’ve answered a question for you, perhaps you can help me with this issue – I have asked you above whether the form won’t mess up my page. Well it did.
    I have a lightbox 2.04 on one page and the contact form coding knocked off the function, so now it does not work at all – aaaaahhh. I am not skilled enough to fix the javascript code. Any suggestions?

    here is the link to my page: http://colemanecreative.com/portfolio.php

  22. January 28, 2010

    Hi Eva,

    You have a very nice website and I love your work. Believe it or not I’m not really that much skilled in Javascript either. Honestly, I hate JS. hehehe. What you can try is also use jQuery for your lightbox functions just to avoid Prototype/Scriptaculous functions from conflicting with jQuery. Hope this helps and good luck.

  23. February 5, 2010

    This is awesome! I can’t believe its so easy :) Thanks.

  24. February 9, 2010

    Hi, thanks for the script, pretty quick and handful. I just wanted to say that th functino to validate email format (functino eregi) is now deprecated.

    I solved changing this line:

    } else if (!eregi(“^[A-Z0-9._%-]+@[A-Z0-9._%-]+\.[A-Z]{2,4}$”, trim($_POST['email']))) {

    into this:

    } else if (!preg_match(“/^[_\.0-9a-zA-Z-]+@([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z]{2,6}$/i”, trim($_POST['email']))) {

    it just work fine.

    Thaks again for the good work

  25. February 22, 2010

    thank you for this tutorial but not work on IE5,IE6,IE7

  26. February 25, 2010

    Very good tutorial :)

  27. Frank permalink
    February 28, 2010

    I love this – it works great with one problem; it fires off an email (with blank fields, of course) when the page loads. Once the fields are filled out and submit is pressed it works perfectly.

    I think the problem is this:

    When the page loads the first two functions seem to load. The first function will only trigger if there was a Submit, which there isn’t. The second function will actually run because the hasError variable was never initiated and does NOT resolve to ‘true’.

    I don’t know how to fix it though. Any ideas?

    Thanks for all your time and effort.

  28. Pauline permalink
    March 2, 2010

    Hello,
    I’m a french designer, sorry for my poor english.
    I’m trying to use this contact form, here is a test page : http://www.paulinegirondin.com/contact/contact2.php

    But I dont receive the mails I try to send? (I’m looking for the problem from few hours ago!) Can you help me please?

    Do you know how I can put the “error fields” in french?

  29. March 2, 2010

    Genial hasta el momento me ha funcionado!
    voy a intentar crear más campos y si me queda bien coloco el link donde lo pude usar
    Muchas Gracias Raymond!

  30. xhino permalink
    March 5, 2010

    Hi, first awesome tutorial men… thanks to make this things

    Second, im looking for the line that modifies the messages of the validation process, my web site is based on Spanish Language…

    Please i need ur help

Trackbacks and Pingbacks

  1. Formulario de contacto con PHP y jQuery | Código-Fuente
  2. apadmedia.com » PHP Contact Form with jQuery Validation
  3. What Should I Write About? | Raymond Selda
  4. Web Form Validation: Best Practices and Tutorials | Desinine
  5. Web Form Validation: Best Practices and Tutorials « Ramesh
  6. Web Form Validation: Best Practices and Tutorials | Results videos photos news blogs At I google wiki . com
  7. Web Form Validation: Best Practices and Tutorials — missrix
  8. Web Form Validation: Best Practices and Tutorials
  9. The Blog of Hanas › Dave Hanas finds random links around the web
  10. This Week in jQuery, vol. 5 | Jquery Cave
  11. This Week in jQuery, vol. 5 « Articles
  12. Web Form Validation: Best Practices and Tutorials « Smashing Magazine
  13. 10 Useful jQuery Form Validation Techniques and Tutorials : Speckyboy Design Magazine
  14. 25 jQuery Tutorials for Creating and Working with Forms « Freelance Web Designer from Hyderabad, India.
  15. Web Form Validation: Best Practices and Tutorials | WebsGeek
  16. 10 Useful jQuery Form Validation Techniques and Tutorials « Om Net Solution
  17. 25 jQuery Tutorials for Creating and Working with Forms | Son Of Byte - Web Design & Development

Leave a Reply

Note: You can use basic XHTML in your comments. Your email address will never be published.

Subscribe to this comment feed via RSS