PHP Contact Form with jQuery Validation

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.

Categories: PHP

274 thoughts on “PHP Contact Form with jQuery Validation

  1. @We Love Webdesign: Thank you for the comment. You are absolutely right on using fieldset instead of a div for wrapping up the form. My bad! hahaha.

    @Jason Armstrong: Thank you for your comment.

  2. @Jitendra Vyas: Please check your spam folder. I noticed that Gmail tends to classify the email as spam. I tried using a Yahoo mail and everything was sent to my inbox. I guess this has something to do with the headers from the email.

  3. You might want to wrap the input in the label tag too. Some people prefer that method, however you’d need to wrap the label’s text in another tag, or add some more styling to the strong tag to format it in the correct manner.

    Ideally you’d submit the form to another php page too, because if someone refreshes after sending an email it’ll send it again.

  4. Hello Mariano,

    I’m here to help. What do you mean by “it just didn’t work”? What message did you get after you submit the contact form? Did you get the info details from the contact form to your email? I sent a message using the contact form you provided in the link and I got a confirmation message that my email was sent.

    I also tried what you did by copying the finished code. I changed the email and it worked out just fine.

    I can help you more if you can provide additional details. Thanks.

  5. Try checking your spam folder. If nothing really works out just double check everything and try out different email addresses or just try different approaches. Sometimes you really have to troubleshoot in order to find out what’s really happening. Thank you and good luck

  6. Great Tutorial!

    I was just wondering if i could put the PHP code in a seperate file and include that file into my HTML file?

    If so how may i go about doing it?

  7. @Randy: Yes, you could try putting the PHP code into another file then include it at the topmost part of the file that displays the form. Just make sure that all files are in PHP. Let me know if you’re successful with that. Thanks.

  8. Thanks for the tutorial. Now i am implementing most of your code within my client website! as they doesn’t require a very dynamic website (which i prefer to use WordPress, usually), your code seem to fit the bill for most of the basic website need today. Thanks Raymond!

  9. Great tutorial….really helpful! I have a question….how would i add and send “auto reply” message to the end-user? I’m fairly new to PHP!

    Thanks for you help in advance!

  10. @Shaun: You can add the “auto reply” message by writing another mail function that will send a message to the user. I hope that made sense. Thanks for your comment.

  11. thanks for the reply….as i said i’m a bit new to new to PHP and as it does make sense…i’ve tried to pull it off but it’s not working for me…here’s my example:

    $emailTo = 'info@jac-n-rum.com' . ', ';//email to info
    $emailTo .= 'jacnrum@gmail.com';
    $body = "Subject: $subject \n\nFirst Name: $name \n\nLast Name: $lname \n\nAddtional Guest: $addguest \n\nEmail: $email \n\nComments:\n $comments";
    $headers = 'From: '.$name.' '.$lname.' '; //(for reply to) . "\r\n" . 'Reply-To: ' . $email
    mail($emailTo, $subject, $body, $headers);


    $to = '$email';
    $subject = 'My subject';
    $message = 'Hello world!';
    $headers .= 'info@jac-n-rum.com';
    mail($to, $subject, $message, $headers);

    $emailSent = true;

    can you tell me what i may be doing wrong?

    thanks in advance!

  12. @Shaun: Glad to know you’re trying things out and making it happen. I like your idea and I know you can make it work. I tried the same thing and this is what I came up with:


    $emailTo = 'mywonderfulemail@gmail.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);


    $body = "Name: $name \n\nEmail: $email \n\nSubject: $subject \n\nComments:\n $comments";
    $headers = 'From: domain.com < '.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
    mail($email, $subject, $body, $headers);

    $emailSent = true;

    I put the $email directly into the second mail function. This one works with both gmail and yahoo. Try this one and let me know how you kicked ass! :-)

  13. Hi, Raymond,

    I used your code in my project, but the request field text: “This field is required.” is in english, but i need put in portuguese. Did you help me please, how do that?

    Best regards and good work!
    Abreu

  14. Hi Raymond,

    I was wondering if Randy got it working linking it to a Contact.html page rather than PHP page?

    We’re working on a site that doesn’t have PHP on the hosting but just want to point the form to execute on another server location that has PHP hosting.

    Example:
    Contact.html will be part of the site. And form to post through to contact-form.php on another server

    I’d like to do it this way rather than using an iFrame. Have you any suggestions apart from just making the files PHP?

    Thanks,
    Scott

    @Randy: Yes, you could try putting the PHP code into another file then include it at the topmost part of the file that displays the form. Just make sure that all files are in PHP. Let me know if you’re successful with that. Thanks.

  15. Hi Scott,

    I think you cannot call it from another server. The files should reside in the same server. If you don’t have PHP in your server, you could try to process the form the old school way by using CGI. I never tried it though.

  16. Hi, great tutorial – really clear and you have gone though the process stage by stage but, I’m still stuck.
    I copied the code, saved it into a file called contact.php and changed the email to my own. I then uploaded this file along with the jquery.validate.pack and tested it entering http://www.lexinc.biz/contact.php.

    when I come to that address all I can see is code on a white background, no form to be found!?
    soooo frustrating, i’m obviously doing something daftly wrong and I’m sure its simple…please help!
    the hosting package include php…

    what could be the problem, I would be most grateful for a response! thanks, Lloyd

  17. Hi Lloyd,

    That is a weird one. Are you sure you have PHP in your hosting package? Try to make sure by creating a new PHP file (whatever filename you want) and put:


    <?php phpinfo(); ?>

    It should output the information in your PHP. Can’t think of anything else why this isn’t working for you.

  18. Hi Raymond,
    I found out that the hosting package didnt support PHP!! argh!
    Just one other thing, the form looks different between firefox and IE….In firefox if you dont enter the required information it comes up under the field box saying “information required” whereas in IE, it comes up with the informaiton at the top of the form “Please check if you’ve filled all the fields with valid information…etc”

    Is there are reason that it is different?

    Thanks for your help, I really appreciate it – if you need to show people working examples please refer them to http://www.lexinc.biz if you need.

    Lloyd

  19. Hi Lloyd,

    Good thing you figured that one out. Your site’s contact form is looking nice. I believe it’s the plugin’s feature that’s causing that behavior in IE6. It’s nice because it has an extra support for IE6. Looks okay in IE7 and 8.

  20. Hi Coffee,

    I’m glad you already visited the documentation page. Just do and follow the example code. Nothing will really happen if you just stare at it. 😉 Good luck and please let me know if you’re still having problems.

  21. Hello I tried 5 different forms and i get a error either

    Warning: mail() [function.mail]: SMTP server response: 554 The message was rejected because it contains prohibited virus or spam content in D:\———–form.php on line 19
    or
    Warning: mail() [function.mail]: SMTP server response: 451 See http://pobox.com/~djb/docs/smtplf.html. in D:\———-contact.php on line 45

    this form gave me 451

    i added the ———- but i don’t think its the code.Ive did some reading and SMTP come up also im with Godaddy.

  22. Hi Raymond,

    first thanks for your request and for this nice script.

    I dont only stare at the page, I try a many times a many things. But I just dont understood how and where to put the code which is wirtten there:

    $(“.selector”).validate({
    rules: {
    name: “required”,
    email: {
    required: true,
    email: true
    }
    },
    messages: {
    name: “Please specify your name”,
    email: {
    required: “We need your email address to contact you”,
    email: “Your email address must be in the format of name@domain.com
    }
    }
    })

  23. Hi Coffee,

    Nice to know you’re trying things out. I also tried to work this one out and I have to admit that it’s kinda tricky. After trying a few things out, I finally got it to work. Just change your code (head section) to:


    <script type="text/javascript">
    $(document).ready(function(){
    $("#contactform").validate({
    messages: {
    contactname: "Please specify your name",
    email: {
    required: "We need your email address to contact you",
    email: "Your email address must be in the format of name@domain.com"
    },
    subject: "Please enter a subject",
    message: "Please enter your message"
    }
    })
    });
    </script>

    Try it and please let me know your results. Thanks and good luck.

  24. Hi Raymond,

    what shall I say, you put the sugar in my coffee, now it taste good. I thank you very much, it works.

    There is just one little more thing for betterment, after the mail was sent, it is possible to refresh the page which send with every reload the mail again.
    When the mail was sent, how I can redirect to another page after a few seconds?

  25. Good to hear it’s working Coffee. As for the redirection, one way to accomplish this is you can put a header redirect function header("Location:http://www.domain.com/page.php") after the conditional statement that checks whether the email is sent inside the body. Try that one. Good luck.

  26. this script is great and works well on my server, however, I get the following error message when I upload it to the clients server. Could it be because their host doesnt support php? cant think of another reason???
    Notice: Undefined variable: subject in \\NAS42ENT\domains\s\s…….

  27. Hi there,

    First off, what a fantastic tutorial. Very clear and easy to follow.

    I’ve uploaded all of my files and everything looks/works great. I just tried to submit a form in IE8 and it didn’t work. The fields cleared, but neither the success/failure messages appeared and no e-mail came through. I’ve submitted the form successfully in both Firefox and Chrome so I’m not sure what the problem could be.

    Thanks again for an awesome tutorial and any feedback you can provide.

    l.

  28. Hi Liz,

    Thanks for the comment. Try to copy and paste the code from this tutorial. I would recommend you write it manually to learn more efficiently but you have to check carefully. Check everything. I’ve tested the form in IE8 and it’s working okay (I received the message and email). Good luck. I know you can pull it off.

  29. Hi Raymond,

    Thanks for the quick reply. After copying the final code at the end of the tutorial, I tried it in iE8 and it worked. I had a look and I figured out what the problem was. I had created a submit graphic to replace the gray box in order to match the look of the page. I was using this:

    IE8 didn’t like that very much.

  30. Hi Raymond,

    First of all, I would like to thank you for this great tutorial!

    Second, I have this problem with cyrillic text. When I tested the form by typing in cyrillic text, which is important for me, and sent the message, I received complete nonsense like: привет instead of the cyrillic text. Can you help me?

  31. …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

  32. 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?

  33. 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!

  34. 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….

  35. 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.

  36. 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..

  37. 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).

  38. Great, label.error was what I was looking for….Thanks for the great tutorial (especially having it all in one file)

  39. 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…

  40. This was the best mate, thank you so much for providing such handy code and presented with best manner.

    regards,

  41. 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

  42. 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?

  43. 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.

  44. 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!

  45. 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.

    1. 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.

  46. 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?

  47. 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!

  48. 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

  49. 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

  50. 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.

  51. 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

  52. Works perfectly. Thank you for this small and simple to implent contact form. The many comments with your reply also helped a lot.

  53. 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

  54. 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 :o)

  55. 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

  56. 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.

  57. 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.

  58. 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!

  59. 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!

  60. 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

  61. 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.

  62. 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

  63. Sorry you’ve already answered my question. All you have to do is add the css tag – label.error
    Thanks for sharing.

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

  65. 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 ?

  66. 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:

    ";
    } ?>

  67. 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

  68. //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

  69. 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

    1. 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.

  70. 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.

  71. 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.

    1. First, THANK YOU Raymond, for this amazing code, really great!

      I was reading every comment since 2009, and at last i found my problem.
      Paul have the same problem that i have. I receive the same email every time i refresh the browser.

      any reply for this?

      Thank you again

  72. 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

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

  74. 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!!

  75. 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!

    1. 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.

  76. 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

    1. 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.

  77. 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

  78. 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.

  79. 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?

  80. 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!

  81. 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

  82. Thx! One little thing:

    Name:

    should be

    Name:

    ( Change for=”name” to for=”contactname” in order to activate the input field with a click on the label “Name”) Hope you get what I mean 😉

  83. Hey, I love this tutorial and I am about to implement it into a new design. I kept getting my mail in my spam folder in gmail so I changed the $headers line to $headers = ‘From: My Site ‘ . “\r\n” . ‘Reply-To: ‘ . $email; – works great now!

  84. just wanna ask..why is that everytime i fill up the form i didn’t received any message to my email..all i want is after fill-up the form…on my yahoo mail “jheyven_05@yahoo.com” will send directly the message that i put it on the form?? how can i do this???

  85. Great tutorial, it works great, but I have one question…
    Is it possible to set up custom error messages like PLEASE TYPE YOUR NAME instead THIS FIELD IS REQUIRED ???

    Thanks

  86. Hello Raymond. My question is: I’ve test the form on a Linux server and the email arrives ok… but I’ve also test on a Windows Server, and the mial doesn’t arrives…. I mean.. the email seems to be sent, but nothing arrives… Any suggestion?

    Thanks and regards

  87. This is great work..

    Just need to know, how can we give custom error message for particular text field? Say, a textfield is username and I want to show message “username can’t be empty” something like this.

  88. Firstly.. thank you so much, I really appreciate the effort put into making this tutorial so easy to understand.. It is exactly what I wanted :). I have got the script working perfectly but I have a query. Is there a way to display the thank you message ( or the error message) in a pop up style dialogue box, like within a JQUERY UI style box instead of displaying it in the default position above the form. If you see http://twitaflick.com/avatar and click contact you will see why I require this. Once a user hits submit, the page is reloaded and no thank you message is displayed unless they were to press contact again, as the contact form is within a slide panel located at the top of the page. If a pop up message was to appear it would be cool and solve a problem :)

  89. thanks for the wonderful form, works like a charm! I do have a question though. I wanted to add a couple of fields that aren’t required. I really don’t know php and only just found out you can’t lookup php code by looking in the source :-)

    I was reading through the comments but couldn’t find the solution. Could someone help me out with the code?

    Thanks in advance!
    Will

  90. I also had the problem, that no mails came in. Perhaps you can solve the problem by changing the settings in the administration of your provider. I had to define a mail address as default first and then it worked.

    P.S.: I`m from Germany, so please excuse my bad english.

  91. I also had the problem that no mails arrived. I could solve it by changing the settings in the administration area of my provider (hosteurope): I had to define a mail address first as default.

    P.S. Excuse my bad english. I`m from Germany…

  92. Great tutorial, many thanks!

    Just wondering if its possible to change the background colour of the ‘Send Message’ Submit button?

    Many thanks,

    Damien :o)

  93. This was the best tutorial i found on the topic – simple, well structured and explanatory, thank you so much. My current assignment got a lot easier.

  94. Hi there, thanks for the tutorial.
    However, have you check the finished code?

    It has errors:
    ‘ . “\r\n” . ‘Reply-To: ‘ . $email; mail($emailTo, $subject, $body, $headers); $emailSent = true; } } ?>

    That sits on top of the form when finished? Missing some code in the top part of the PHP code. What would you recommend?

  95. Hi. Great Tutorial!
    Just want to ask, how do i edit the error message?
    For example “This field is required.” to “Please enter username”.

  96. I was wondering how, instead of the email being from “My Email” if you could make it from the email entered in the form. I tried putting a ‘$email’ after $headers = ‘From: but it just made the text ‘$email’. I also tried copying the ‘ . “\r\n” . ‘Reply-To: ‘ . $email; and changing it to $emailFrom but I got an error. I’m sure this is a simple thing to do, I’m bad at php. I apologize if this has been addressed already. Thanks for the tutorial!

  97. Why after i press the send button the text with the thanks message doesn’t appear?
    Can anyone help me?

    This is the code:

    <?php
    //apas pe trimite

    if(isset($_POST['submit'])) {

    //nume este gol?
    if(trim($_POST['nume']) == '') {
    $hasError = true;
    } else {
    $nume = trim($_POST['nume']);
    }

    //prenume gol
    if(trim($_POST['prenume']) == '') {
    $hasError = true;
    } else {
    $prenume = trim($_POST['prenume']);
    }

    //telefon gol
    if(trim($_POST['tel']) == '') {
    $hasError = true;
    } else {
    $tel = trim($_POST['tel']);
    }

    //adresa mail valida
    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']);
    }

    //comnetarii
    if(trim($_POST['message']) == '') {
    $hasError = true;
    } else {
    if(function_exists('stripslashes')) {
    $comments = stripslashes(trim($_POST['message']));
    } else {
    $comments = trim($_POST['message']);
    }
    }

    //formular corect trimite mail
    if(!isset($hasError)) {

    $sendTo = "kondrei@gmail.com"; //adresa la care vrei sa se trimita mesajul
    $subject = "Mesaj de pe site-ul WoodArt";
    $headers = "From: " . $_POST["nume"] . " " . $_POST['prenume'] . " \r\n”;
    $headers .= “Reply-To: ” . $_POST[“mail”] . “\r\n”;
    $headers .= “Return-path: ” . $_POST[“mail”];
    $message = ”;
    $message = ” Nume: “.$_POST[‘nume’].”\n Prenume: “.$_POST[‘prenume’].”\n Telefon: “.$_POST[‘tel’].”\n E-mail: “.$_POST[’email’].”\n Mesaj: “.$_POST[‘message’];
    mail($sendTo, $subject, $message, $headers);
    }
    }
    ?>

    WoodArt – Contact

    $(document).ready(function(){
    $(“#contactform”).validate();
    });

    label.error {
    font-weight: bold;
    color: #742c30;
    }

    Home
    Produse
    Tehnologie
    Garanţii
    Recomandări
    Contact
    ENGLISH

    Please check if you’ve filled all the fields with valid information. Thank you.

    Vă mulţumim pentru mesaj!
    Un coleg vă va răspunde la solicitare în cel mai scurt timp posibil.

    Contacteazã-ne!
     

    Showroom

    BucureÅŸti, Str. EpureÅŸti, Nr. 11
    Tel./Fax 021.668.47.26, 021.668.47.30

    Producţie
    FloreÅŸti, Jud. Cluj, Str. prof. Ioan Rusu, Nr. 3
    Tel. 0264.265.530, Fax 0264.265.150

     

    Solicitare ofertă de preţ
    <form method="post" action="” id=”contactform”>

    Numele tău:

    Prenumele tău:

    Telefon:

    Adresa de e-mail:

    Message:

    * Toate câmpurile sunt obligatorii

    Copyright, 2010 SC General Comexim SRL  • 
    Developed by MediaOne
     •  Valid
    XHTML
     •  Valid
    CSS

  98. I have got right to the end of this tutorial. Then when I put the PHP above the Doctype and previewed it in browser.

    The form did not display at all only the PHP code I pasted in.

    It looks just like yours I’m not sure whats going on.

  99. Hi guys, good job really usefull and easy to costumize thanks for share it.
    matvespa try in jquery.validate.pack.js looking for the words in the example of message error.

    dan Bad sintaxis mate just check the code.
    Justin Gray is very easy just try to understand what Raymond is doing.
    The code is fully commented if you try and you get some is better than just ask :).

    Good luck!

  100. I’ve tried looking in the folder ( jquery.validate.pack.js ), but it’s all keywords! I know there’s a easy method for that but I did grasp the coding part of it yet..

    Look at the source of this site, you see that they changed the error description
    http://jquery.bassistance.de/validate/demo/

    Anyone can bring some methods on how to achieve this ?

    thanks.

  101. I got it working with my own error comments. I also tried by erasing the javascript and it gives me the simple php error, so it works if someone dosen’t have the javascript enable.

    Now the form is up to my expectation but I would’nt of been able without this script. Thanks again.

    If someone needs help setting up their own error comments, I’ll be willing to help :)

    Justin.

  102. hi,

    I’m trying to modify the error message but didn’t know how to do it.

    Instead of This is a required field” I need it to change something like… “Name of the field” missing

    how can I place the Label of the field in the error message?

    Thank you, by the way this is a great tutorial :)

  103. Has anyone successfully moved the errorElement? I have the labels and input fields on separate lines and I would like to have the errors appear next to the labels.

    I also figured out how to change the errors from being a label to a span, but cannot figure out how to remove the attributes such as “for” or “generated” without breaking the script.

    Can someone who’s good with jQuery lend me a hand?

  104. Great tutorial, forms have baffled me for so long and finally I think I can make sense of it all!

    I was just wondering, how effective this form would be against spam and also can I make input type=”hidden” or would that not work?

    Thanks

  105. @sarah

    If you want custom error fields, it would require some tweaking. The following is a short tutorial for those of you who would like to modifiy the error messages. By the way, if you would like to change the style of the error message, it’s all done within your stylesheet with the “label” tag.

    The form itself is like Selda’s except there’s no class for the required, so build your form without them but remember to give your fields unique ID’s.

    Within the header of your contact page, you will need the following links, which are provided by Bassistance :

    Like Selda’s, you will need to put the following above the doctype ( This is an example of the error messages or optional fields, modify to your own requirements. ) :

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

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

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

    //This one is optional, I added the striplashes to take out the / when " or ' is added.
    if(function_exists('stripslashes')) {
    $car = stripslashes(trim($_POST['car']));
    } else {
    $car = trim($_POST['car']);
    }

    //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']);
    }

    //If you don't want the striplashes, simply place the last line of the 2nd else statement.
    if(trim($_POST['message']) == '') {
    $hasError = true;
    } else {
    if(function_exists('stripslashes')) {
    $message = stripslashes(trim($_POST['message']));
    } else {
    $message = trim($_POST['message']);
    }
    }

    //If there is no error, send the email
    if(!isset($hasError)) {
    $emailTo = 'name@business.com'; //Put your own email address here
    $subject = 'New comment received'; //Put your own subject here
    $body = "Name: $name \n\nEmail: $email \n\nTelephone: $phone \n\nCar: $car \n\nMessage:\n $message";
    $headers = 'From: My Website ‘ . “\r\n” . ‘Reply-To: ‘ . $email;

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

    Next we will place the error message in PHP in case the user has deactived javascript for some reason and we will place the Thank you message that will appear above the form. Both of theses could be placed above your form in contact.php…

    Error message:

    Please check if you’ve filled all the fields with valid information. Thank you.

    Thank you message:

    Email Successfully Sent!
    Thank you for your interest in our site. I will contact you shortly if needed.

    That’s it. Here’s a little help for the css styles, but you can add your own to .error and label:

    label {display:block;float:none;width:auto;}
    .error {color:#ad0000;}

    Hope this will help some of you.

  106. Sorry, forgot to add an important detail!

    Below the scripts add the following to edit your error messages. For the fields that are optional you do not add them here. Don’t forget to change the “#yourformid” to your own id :

    $().ready(function() {
    // validate signup form on keyup and submit
    $(“#yourformid”).validate({
    rules: {
    name: “required”,
    email: {
    required: true,
    email: true
    },
    phone: “required”,
    },
    messages: {
    name: “Please enter your firstname”,
    email: “Please enter a valid email address”,
    phone: “Please enter a phone number”,
    }
    });

    });

  107. Hi Raymond,

    I am using GoDaddy hosting and once i have submitted the form on their servers, it says it sends but i receive no email at all.
    Plus at the top of the screen, i receive this error message:-

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

    Line 45 appears to be – mail($emailTo, $subject, $body, $headers);

    Are you able to be of any assistance? Thank you.

    Regards,

    Richard

  108. @Jason, you cannot preview php-code in the browser, it is a server-side script and has to be compiled by a server which has php installed. So you need to upload the file to a web-server with php and then type in the address in the browser to that file to see it rendered as it should. Another way you can do it is to install a wamp (windows) or mamp (mac), a package with web server, php and mysql and then you can test it on your own computer.

    Good luck!

  109. This in your tutorial is the most important sentence: “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.”

    It´s a matter of security to validate in two steps. Javascript will be executed on the clients machine and it is not secure to let the user validate the data you need maybe for sending an e-mail. A client e.g. can build a own little page without validation and send you some shit just as an attack …
    So it must be to have two way validation!

    I tip: Use REST-api for validation. Send the form-data via JS to the api (which is maybe written in PHP) and let it do the tests. Later you can reuse the validation functions in PHP before you send the E-Mail!

    I´ve done a little tutorial with jQuery and CodeIgniter:
    http://www.karrock.de/daf/2009/10/how-to-validate-forms-with-jquery-and-codeigniter/

  110. Many many thanks for sharing this form ! It was so much help. Finally I got a form working : ) I still need to change the “this field is required” field to spanish but I already read all questions and comments and found your explanation to “Coffee”. Tomorrow I’ll try it and I’m pretty sure it will work since everything you share with us did.

    THANK YOU!

  111. The whole point of using Ajax is to improve interaction and feedback to users. So please don’t wait to validate forms before the user presses the send button.

  112. I would like for the script to send an auto response to the senders email address. How do I do this please. Please indicate where exactly to put the code. I’ve been trying to add another mail() to the script but it stops the page working…

  113. @Richard (and anyone else who is on a Windows/IIS server at GoDaddy or anywhere else):
    You will need to change all instances of “\n\n” in the email scripts into “\r\n” due to differences in the way that Linux/Unix servers and Windows servers process line feeds.

    Thanks to Raymond for putting this together – made things quicker and easier for me today.

  114. hi

    brilliant tutorial really clear and well documented

    I get the php validate messages ontop of the contact form when I load the page in a browser??

    can this be fixes? surely these messages should only show up when you click send and nothing is added in each input field??

    Thanks in advance for any help

    b

  115. Thanks. Worked great!

    I made a slight adjust to make sure no ugly php errors and warnings where thrown at the top. Instead, if there were errors, they were displayed nicely in the form.

    1) Changed the php.ini config by adding this line to the top of your code….

    ini_set(‘display_errors’, 0);

    2) Then, added error notification in the header’s javascript

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

    if (mail($emailTo, $subject, $body, $headers)) {
    $emailSent = true;
    } else {
    $emailSent = false;
    }

    }

    3) Added this line in the html above the form

    Email Was Not Sent!
    If problems persist please contact us and let us know!

  116. err sorry.. my #3 turned into html … let me repost

    3) Put this above the form

    Email Was Not Sent!
    If problems persist please contact us and let us know!

  117. Hello, Contact Form is very Nice and well executed, but when i use this i found some error while sending email, it is giving error like this

    Warning: mail() [function.mail]: Failed to connect to mailserver at “localhost” port 25, verify your “SMTP” and “smtp_port” setting in php.ini or use ini_set() in C:\wamp\www\Contact_Form\contact1.php on line 45

    and 1 more, i didn’t able to find “This is required”, i have to replace with “User name required”…

    If you will have time then please help me, you can send solution on my email id, i will wait for your response.

    Thanks and Regards

    Devendra Pawar
    devendra.pawar@quadrabiz.co.in

  118. Great tutorial. This is perfect for my site. Just one question. How would I go about having the error messages appear above the form fields, and next to the name of the field rather than below the form fields. I managed to absolutely position the ‘label.error’ css value to minus co-ordinates, which does work, but there must be a simpler way to achieve this. Something in the order of the way the html form code is placed. I can’t seem to work it out though.
    Any help with this would be appreciated.

  119. Great tutorial – but hoping to expand the form to include a newsletter signup checkbox. I don’t know how add that so it emails if the the checkbox was selected or not? Any help would be much appreciated – I’ve been trying to figure it out for way too long!

  120. I gave this an honest shot. I want to use the form to redirect the user to another page where they can download an ebook while the email sends me their contact information. After some troubleshooting, I finally got the form to submit without error and to redirect to the download page. BUT, the email that’s sent to me is devoid of the required information. This is what I get:

    from xxxxxx@xxxxxx.bluehost.com
    to download@mysite.com
    date Wed, Oct 6, 2010 at 5:26 PM
    subject xxxxxx Download

    First Name:
    \Last Name:

    Email:

    Phone:

    Organisation:

    This is the mailing code I used:

    //If there is no error, send the email
    if(!isset($hasError)) {
    $emailTo = 'download@mysite.com'; //Put your own email address here
    $subject = "xxxxxx Download";
    $body = "First Name: $first_name \n\Last Name: $last_name \n\nEmail: $emailaddress \n\nPhone: $phonenumber \n\nOrganisation:\n $organisation";
    $headers = 'From: My Site ' . "\r\n" . 'Reply-To: ' . $email;

    mail($emailTo, $subject, $body, $headers);
    header( "Location: download-xxxxxx.html" ) ;

    Can someone PLEASE point me in a direction I can find out why I’m not receiving the information in the email?

  121. @Sherwin

    I had this problem but after having a fiddle I found a working solution.

    Simply replace:

    $headers = ‘From: My Site ‘ . “\r\n” . ‘Reply-To: ‘ . $email;

    With:

    $headers = “From: {$email} “;
    ————————————————————————————-

  122. Great plug-in! I merged it into wordpress, and also popped it into a thickbox with no problem. Thanks for sharing.

  123. Is there a way to add 2 of these forms to the same page. I want to use for both a simple newsletter signup in the left column that just takes an email address and is on every page. Then I want to use it for a full form on the contact page with many fields. The problem I am having is that when you get to the contact page and it has the newsletter signup in the left column as well, it gives a “false positive” to the newsletter signup if the user fills out the contact form. Any help would be great. Thank you.

  124. I figured out the above issue, but now running into another issue. I added several new fields and now it is giving me an error saying i have not filled out all the fields. If anyone can help me with figuring out this problem I would appreciated it. I can post the code here if needed but hate to take up too much room in the comments. Thanks.

  125. Hi,

    Great tutorial but…

    Is there a replacement for the !eregi bit (in the email field validation) because that’s now deprecated in PHP 6??

    Any help would be greatly appreciated!

    Thanks

  126. Hi, first, let me thank you for a great job! Really simple to deploy.

    Now i need more help :). I need to show a jquery.message only if the form is valid. I´m stuck here:

    $(document).ready(function() {
    $(“#contactform”).validate();
    $(“#contactform”).submit(function() {
    $().message(“Gracias por su consulta, en breve lo contactaremos para asesorarlo.”);
    return false;

    });
    });

    Any help would be very appreciated.

    You can see it working @ http://www.martrans.com.ar/nuevo/nuevo/es/cargas.php

  127. I followed this guide stpe by step and implemented it on my contact page on my own website. When you submit the message this message shows up at the top of the screen and no email arrives to my inbox

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

    Any idea on how to fix this?

  128. Thanks a lot for the tutorial.
    I’ve one question:
    can we use recaptcha in this form.

    Thanks again.

    Regards

  129. Hello
    I am struggling to incorporate a redirect via either [php] header(); located after the mail() command, or [javascript] window.location within the $(form).validate(); function.

    I can get the email to send without redirect or I can get it to redirect without sending the email. It looked like someone earlier was able to get it to do both, but it would appear that perhaps a setting in the javascript or in the form declaration was also revised. Does the form action=”” need to change from PHP->self to something else maybe? HELP!!!

  130. not to be a pest but I am also using jquery to prompt the field values so I don’t need to put labels in them
    for instance:
    $("#middleinit").focus(function () {
    $("#middleinit").val('');
    });
    $("#middleinit").blur(function () {
    if($("#middleinit").val() ==''){
    $("#middleinit").val('Middle Initial');
    }
    });

    This means that the field label is in the field until a user fills it out. if a user clicks on the field the label in it disappears and if they move to another field without entering it fills in the field with the label again.

    The problem I am having is that if the form doesn’t validate it wipes the information a user has entered. I want to know how to access the values of the fields that do validate so I can keep them filled out when the form validation fails.

    thanks again for the form and for the further assistance.

  131. got the redirect issue fixed- embarrassingly enough, I just had to move the php to the top of the page before the html. Had that happen enough in the past that I shouldn’t have made the mistake again.

    still hoping for some kind of fix to keep valid fields filled out when invalid fields break the submit process. thanks.

  132. Hey! A nice form that works great too – result!

    Can anyone point me in the right direction for setting it up as an html page with the php in an externally referenced file? Is that easy to do or would it be a complete nightmare? The whole php thing is still a bit of a mystery to me…. = )

    Thanks for sharing this great code!

  133. how can i insert an uploader into this form?
    i’ve to upload 4 image on the server and the name of each image must to be sent in the email.

    anyone can help me?

    thankyou

  134. I tried to use your contact form, however, the problem when I tested was I couldn’t get the email from the sender. Please advise!!! Thanks

  135. I tried this way but didn’t work neither. Anyone have a better idea? Please adivse!!!

    Simply replace:

    $headers = ‘From: My Site ‘ . “\r\n” . ‘Reply-To: ‘ . $email;

    With:

    $headers = “From: {$email} “;

  136. OMG Im so thankful for this ! its perfect and works great, the tutorial its so easy to understand. Just what i needed. THANK YOU SO MUCH FOR THIS !

  137. So, how do I implement this into a lightbox? I am building a site but I don’t want a full dedicated page for a contact form. The code works for validation, but I want it to pop up. I see you got it to work, Ken. Can you (or anyone) assist me in placing in a lightbox? I’ve tried to download and follow instructions for prettyPopin, lightbox, etc.. but not sure how to go about it.. Thanks for any help guys!

  138. Hi,
    first of all thank you for sharing this. I’ve been looking for a solution like this and this is a great tutorial.

    I initially found myself with the same problem that Marcus did.
    ““Warning: mail() [function.mail]: SMTP server response: 451 See http://pobox.com/~djb/docs/smtplf.html. in D:\Hosting\7009516\html\contact.php on line 45″”

    After a little bit of research I found that if the “from” email is one from your domain this problem disappears. You still get the senders email on the message, so my solution was to create a bespoke email address on my domain for comment sending.

    may not be the most elegant solution but it works.

  139. great tutorial, workink nice, addition to this script

    $headers = ‘MIME-Version: 1.0′ . “\r\n”;
    $headers .= ‘Content-type: text/html; charset=utf-8′ . “\r\n”

    to work with UTF-8 encodes ,

    if(!isset($hasError)) {
    $emailTo = ‘kontakt@gradac-apartments.com'; //Put your own email address here
    $body = “Name: $name \n\nEmail: $email \n\nSubject: $subject \n\nComments:\n $comments”;
    $headers = ‘From: My Site ‘ . “\r\n” . ‘Reply-To: ‘ . $email;
    $headers = ‘MIME-Version: 1.0′ . “\r\n”;
    $headers .= ‘Content-type: text/html; charset=utf-8′ . “\r\n”;

  140. @ luke and those looking to fix the “eregi depreciated” error:

    use preg_match instead

    replace

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

    with

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

    That should fix it all up

  141. Hi.. very usefull….!!!… one question.. How or where can I traslate tags like “This field is required.” or others??….
    Thanks very much

  142. Hi! I would like to add more fields. How can I do that? I’ve been trying to add a last name field, for example and it doesn’t work properly! I need to put some extra fields for “city”, “job”, “telephone” and few others… Also, if someone knows any way to include a submit field for attach a .pdf or .jpg file would be great! Thanks a lot for this great tutorial and thanks in advance for your reply!

  143. i tried to add radio buttons but keep getting ‘udetermined’ instead of my variable coming through

    any ideas?

  144. Hi everybody! I´m from Argentina and we use the accents and the “ñ” letter, I’m testing this great form and I like it!! However I’ve a problem with special characters: Does it support utf-8? How can I set up it? Anybody can help me? Thank you very much!

    I would greatly appreciate an answer to my query.

  145. Thank you,
    Just wanna say that this is really a fantastic job u r doing. Just keep it up, i appreciate your hard work and am glad to have this form used.

    Once again,

    Thank you very much!

  146. Nice code and tut.

    One thing that’s causing me probs is that if you fill out the form and click submit, the page is refreshed.

    Any way round that?

  147. Hi I’m using the form exactly as explained and have read all of the comments looking for deprecated PHP, but I can’t seem to get the form to send emails. I had it working in a test location, but now that it’s in the root directory it’s not working for some reason. Any help would be greatly appreciated. Thanks for the hard work regardless!

    belcosupply.com/contact.php

  148. One of the best tutorials. Well done! I’ve used with contact form very easily. Usually it takes so long to make it and finally is not working after a big process. Is that possible to ask the author to add recaptcha also please?

  149. Hello Raymond,

    Thank you SO much for taking the time to write this tutorial. I’ve found it invaluable so far. If you will let me know what your paypal account is I’ll be happy to make a contribution.

    They say a teacher usually knows more because “the more he/she teaches the more he/she learns”. Hopefully you’ve learned more by being generous with us.

    Your script is working, and I’m so happy about this.
    A couple of things are not working quite right, though:
    1) The string “This field is required” does not appear under each field as your tutorial shows. This string is linked to the “required” class and jQuery code. Instead, I get a string at the top of the box that says “Please check if you’ve filled all the fields with valid information. Thank you.” – that is being generated through the PHP script, though. So maybe the jQuery validation I’m using isn’t working, and I’m trying to figure out why.
    2) While linking to a jQuery API hosted by Google isn’t really my preference, it works and I can see why you’d use it (speed). I’m using jQuery 1.5.1, which appears to be the latest.

    This is a great tutorial; about a year old, but know that I spent almost 6 months looking for a tutorial like this one. Thanks a bunch.

    Ricardo

  150. This is good form. I’m wondering how to send a multiple-item combo box selection with this form? Keep up the good work.

  151. Thanks for this great tutorial. Worked like a charm from the first time. The comments also made me search less the web for minor improvements. Great work! Take care, and thanks again!

Comments are closed.