PHP Contact Form with jQuery Validation
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:

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.

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.
Awsome form! Will this ever work in ie6?
Thanks!
…to follow on my comment – in ie6, I can get everything to load ok, but you are not able to click and type on any text field
Hey,
Great script thank you. Only problem is that when viewing the demo and trying it on my own site i get a page error in IE6? You know the little yellow icon that is next to ‘Done’ in the status bar..any ideas what is causing that?
I’m really sorry guys but right now I don’t have enough time to wrestle with IE6. Hope you understand.
No prob Raymond – just wanted to make sure it wasn’t something I was doing – checked more into it and it seems other forms that are out there and built w/ the jquery validation don’t play nice w/ ie6 either – just going to use a simple redirect for those users to a more basic page – nice tut! very useful!
Thanks again!
Very Good!
I don’t know if I am lost or just have a brain-freeze but here it goes. In order to have the field validated you said to put in “class=”required”. But then how would you be able to style the required message?? For example if you style the message to RED font then that also means whatever you type in the input box is also RED….
Hi Keay,
When you send the form with errors, the plugin will insert a label (This field is required) with class in the code. You can now style that label using CSS. You don’t have really to put any CSS for the ‘required’ class because it’s needed by the plugin. Hope that answers your question. Thanks for asking.
Thanks for the quick reply. What I mean is I want to style the required field label to RED for example. So when the message comes out, it is visible. But since the class=”required” is inside the input tag, it makes the text inputted RED also….Hope that is more clear on what I am trying to do..
Hi Keay,
Thanks also for the quick reply. hehehe. You will give the red styling to label.error and not to the input tag. If you want to style the input tag you can do so by ‘class=”required yourclass” />’ and then style “yourclass”. Again, if you want to style the ‘field is required’ messages, you can do so by applying CSS to label.error instead. Hope that helps Keay (having troubles pronouncing your name. hehehe).
Great, label.error was what I was looking for….Thanks for the great tutorial (especially having it all in one file)
One more question. How could you go about validating an input field but not have it required? For example the contact number field I want to make it optional but if the user types the number in, I want to make sure it is sanitized but also validated to make sure it’s all numbers..etc…
You can write a custom PHP code or a Javascript code to filter out the field. I’m going to sleep now. hahaha.
This was the best mate, thank you so much for providing such handy code and presented with best manner.
regards,
I followed your tutorial but it causes my pages to take a LONG time to load and it spits out 2 javascript errors in firebug even in your own example page. http://raymondselda.com/demo/php-contact-form/contact.php do you know what those errors mean?
hey i used the code here verbatim and it sends me the email from the form, however with just the text result, the actual form input data is not there. its like the variables are not translating over what they really stand for. any help would be great
Great form! Any way have it set the ‘reply-to’ address as the sender of the results so it would be easier to reply to the person that filled out the form?
Muy buen tutorial..gracias amigo…
Ray, Thanks so much for all the help you have provided as well as the awesome contact form.
Is anyone having trouble with using this on a GoDaddy Server? I can get this to work on a friend’s server, but for some reason, when I transfer everything over and test it out – I get an error:
“Warning: mail() [function.mail]: SMTP server response: 451 See http://pobox.com/~djb/docs/smtplf.html. in D:\Hosting\3320592\html\contact3.php on line 45″
Line 45 is the mail function.
I ran my server’s php info and it reads that I have PHP Version 5.2.5
I also created a blank php page and tested the mail function with something like this:
Success – I got an email.
I can’t figure this out on my own and any support would be greatly appreciated from me and fellow GoDaddy users.
I contacted GoDaddy about the problem. They wern’t much help but recommended the following:
1. specify an outgoing mail server
2. specify the relay hosting server. They said relay-hosting.secureserver.net with port 25 works
3. specify SMTP settings
I’m very new to php and contact forms – any help would be appreciated. Thanks!
Hello, thankyou for this tutorial,
I have one quick question.
i need to use this as part of a joomla project i am currently working on.
I dont feel it is safe to include PHP inside of an article itself.
Is there a way of having all the php, css and html in seperate files?
Thank you for any help you can offer!
Kind regards,
Tom Kiddle.
Hi Tom,
Yeah. I think I wouldn’t include the script inside WordPress articles either. It all depends on the platform that you use. I don’t have any experience with Joomla so I can’t be sure how you would approach it. But I have to say that it can be done using separate files. Good luck with that.
Hi, nice great stuff!
but can I call this jQuery and PHP form validation from external file, like say not embedding all the codes in contact.php because I don’t want my email address to be displayed to everyone?
Hi, excelent tutorial.
I wonder if its possible to use the form inside a shtml, because I need to use includes for the header, menue, and footer and in php documents I can’t.
Thanks!
Hi thanks for the tutorial,
Im having a problem, the form works perfectly by itself but when i place it inside a div it doesnt run the php script?
any suggestions,
Thanks
Thanks so much for this!!!!!
Raymond, I learn best from sample code and your tutorial has been the best.
It is best code of jQuery, but we use jQuery in different-2 in our website i think we have to change coding ..
Is there a way to change the location of the error text?
Ray, THANK YOU SOOOO MUCH for taking the time and energy to share your wisdom, your tutorial is EXCELLENT!!!
I know you are bombarded by requests, but if you have an easy answer would you please help me.
what I am baffled by is-
when someone fills out my contact form on my site it sends me an email (duh) and then when I hit reply…it is (supposed to be) programmed to reply to THEIR EMAIL ADDRESS. which it always did before.
now either I accidentally changed the code, which I have checked thoroughly and appears to be correct:
{
$additionalHeaders .= “\r\nReply-To: $email”;
}
OR MY GOOGLE ACCOUNT HAS LOST IT’S MIND!
because here is EXACTLY what the google email header says when I get an email from my contact form, which is correct:
from My Site
reply-to person_who_filled_out_form@yahoo.com
to myname@mysite.com
dateSun, Sep 13, 2009 at 2:06 PM
subject TESTING RESPONSE
but when I hit reply IT SHOULD go to person_who_filled_out_form@yahoo.com WHICH IS WHAT IT SAYS!!! but instead it goes to me at: myname@mysite.com
why would it suddenly not work…even when it says it will do what I am wanting??
thank YOU…THANK YOU THANK YOU THANK YOU!!!
Lauren
if you want to check out the exact web page SOURCE it is:
laurenrick DOT net/contact_me.php
amazing tutorial,thanks
Hi, I have a problem with the script….
What if I need to add fields???
can I use this?:
<?php
//If the form is submitted
if(isset($_POST['submit'])) {
$date1 = $_POST['date1'];
$fiebre = $_POST['fiebre'];
those are my values!!! as checkboxes…. but I never receive the mail… why??? How can I do this possible?? I need to add 4 checkbox and 1 date field!!!! I'm using this..
Fecha:
<input type="text" name="date1" id="date1" value="” class=”required” disabled=”disabled” readonly=”readonly” />
PLEASE SOME HELP….
oo.. and Sorry my english.. I’m from Mexico.
Hi Raymond,
Thanks for the great tutorial.
After user submits the form, how do you send them to a new page rather than view the same page.
Like, i want to send them to a Thank You page.
thanks
Hi!
I used the header redirect function header(“Location:http://www.domain.com/page.php”) after the conditional if statement, but I received an error. Perhaps I wrote it incorrectly.
this is what I put.
Help!
thanks
Mimi
Works perfectly. Thank you for this small and simple to implent contact form. The many comments with your reply also helped a lot.
This will come handy!
Hi, trying to implement this form but when I submit it always shows the message “Please check if you’ve filled all the fields with valid information. Thank you.” rather than the ajax validation messages….?
any thoughts please?
many thanks
Exactly what I’ve been looking for!
You also pulled off the minimalist design of your website superbly too.
Thanks!
Hi Corey. Glad the contact form was helpful. Thanks for the kind words.
Hi Great tutorial. Very easy to understand. But I have a question.
If you have two forms on a page how can you include them both. Im not sure how to add this function. I think it needs to go in the head before the DOC TYPE code. Really really new to all this.
Thanks in advance
)
R/Sir/Madam
Sir, myself Ashish working as a PHP programmer in greycells. I want to learn jQuery as soon as possible and also sir I have to make such a function that , ” to allow website visitors to search for phrases and words and find pages with content that matches” in jquery and it should run without need of google or any searchengine and sir my website generates pages from database, Sir if its possible then please send me the script as early as possible
Thanks You
Nice Tutorial! Did somebody fixed the problem with IE6 ?
Thanks the form works great, and the style is simple but sweet.
I have one question about the usability of this form. If invalid data is entered a message displays and all information entered in the the form is cleared.
I often fill out a form and forget to add the “@domain.com” in my email. At which point, while using this form I would loose my beautifully composed message.
What are your thoughts about the usability? I hope my form isn’t the only one behaving in this manner.
Okay I tested your demo form and I see the screen shot where it says “this field is required” — I also see the tip about reading the documentation. Sorry for the hasty reply….and I think I understand which part I skipped.
Hey, great tutorial! Got this thing up and running with relative ease.
Question though, my website is setup using jquery to show/hide divs based on the page you’re viewing. Basically, if you’re at index.php#home, you’re on the home page. index.php#contact, you’re on the contact page.
The problem I have is, whenever the form is submitted, it reloads index.php rather than index.php#contact. How can I direct the contact form to #contact?
Thanks!
Many, many thanks for such a useful and readable tutorial! It’s just what I was looking for.
I have a question regarding possible spam issues with the form. I’ve placed the actual PHP submit script in a folder on my server and linked to it with a require_once statement. It works great! I am however a little worried about the possible spam implications of the script (if any). I don’t know enough about how it works to say one way or the other!
I’m probably being very paranoid, but any advice in this regard would be most welcome.
Again, many thanks for taking time to write the tutorial and for sharing the code!
I have everything worked perfectly, but was wondering how to redirect to an anchor within the same page. I am using jquery sliders to direct the user around the page. When I click submit it just reverts back to the initial area when the page is first loaded, not the area where the contact form is. You can view the problem at http://www.unkemptbeard.com
Thanks for the help and awesome tutorial
works great!
Thank you..
i have added it into my wordpress installation within 10 minutes.
good work.
im going to recommend it to my friends.
Hi,
How do I change the colour of “This field is required” so it stands out. I wnat to keep everything black and have the warning message red.
Thanks for your help
Sorry you’ve already answered my question. All you have to do is add the css tag – label.error
Thanks for sharing.