PHP Contact Form with JavaScript Real Time Validation
Posted on April 30, 2009, under JavaScript, PHP,
Bookmark it
This is a PHP Contact Form having an Image Verification (Captcha) and fields’ validator (PHP & JavaScript). It will work best with the right web hosting provider.
First, let’s create the page where the data will be parsed:
form.php
<?php
include_once 'common.php';
include_once 'process.php';
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Contact Form</title>
<link rel="stylesheet" type="text/css" href="style.css" />
<script type="text/javascript">
<!--
function new_captcha()
{
var c_currentTime = new Date();
var c_miliseconds = c_currentTime.getTime();
document.getElementById('captcha').src = 'image.php?x='+ c_miliseconds;
}
function validate(field_name, field_value)
{
switch (field_name)
{
// E-MAIL
case "email":
var email_enter = "<?php echo $errors['email_enter']; ?>";
var email_not_valid = "<?php echo $errors['email_not_valid']; ?>";
if (field_value == null || field_value == "")
{
document.getElementById("email_status").innerHTML = '<div class="field_error">'+ email_enter +'</div>';
}
else
{
if(!regIsEmail(field_value))
{
document.getElementById("email_status").innerHTML = '<div class="field_error">'+ email_not_valid +'</div>';
}
else
{
document.getElementById("email_status").innerHTML = '';
}
}
break;
// NAME
case "name":
var name_enter = "<?php echo $errors['name_enter']; ?>";
if (field_value == null || field_value == "")
{
document.getElementById("name_status").innerHTML = '<div class="field_error">'+ name_enter +'</div>';
}
else
{
document.getElementById("name_status").innerHTML = '';
}
break;
// SUBJECT
case "subject":
var subject_enter = "<?php echo $errors['subject_enter']; ?>";
if (field_value == null || field_value == "")
{
document.getElementById("subject_status").innerHTML = '<div class="field_error">'+ subject_enter +'</div>';
}
else
{
document.getElementById("subject_status").innerHTML = '';
}
break;
// MESSAGE
case "message":
var message_enter = "<?php echo $errors['message_enter']; ?>";
if (field_value == null || field_value == "")
{
document.getElementById("message_status").innerHTML = '<div class="field_error">'+ message_enter +'</div>';
}
else
{
document.getElementById("message_status").innerHTML = '';
}
break;
}
return true;
}
function regIsEmail(field_value)
{
var reg = new RegExp("^[0-9a-zA-Z]+@[0-9a-zA-Z]+[\.]{1}[0-9a-zA-Z]+[\.]?[0-9a-zA-Z]+$");
return reg.test(field_value);
}
-->
</script>
</head>
<body>
<center>
<h1>Contact Us</h1>
<div align="left" style="width: 500px;">
<?php
if(isSet($status))
{
echo $status;
}
if(!$mail)
{
?>
<form name="register" method="post" action="">
<span id="name_status"><?php if($error['name'] != "") { ?><span class="field_error"><?php echo $error['name']; ?></span><?php } ?></span>
<label>Name</label><input id="name" onchange="validate(this.id, this.value);" onblur="validate(this.id, this.value);" size="30" type="text" name="name" value="<?php echo $name; ?>"><br />
<span id="subject_status"><?php if($error['subject'] != "") { ?><span class="field_error"><?php echo $error['subject']; ?></span><?php } ?></span>
<label>Subject</label><input id="subject" onchange="validate(this.id, this.value);" onblur="validate(this.id, this.value);" size="30" type="text" name="subject" value="<?php echo $subject; ?>"><br />
<span id="message_status"><?php if($error['message'] != "") { ?><span class="field_error"><?php echo $error['message']; ?></span><?php } ?></span>
<label>Message</label><textarea onchange="validate(this.id, this.value);" onblur="validate(this.id, this.value);" id="message" name="message" rows="5" cols="31"><?php echo $message; ?></textarea><br />
<span id="email_status"><?php if($error['email'] != "") { ?><span class="field_error"><?php echo $error['email']; ?></span><?php } ?></span>
<label>Your E-mail</label><input onchange="validate(this.id, this.value);" onblur="validate(this.id, this.value);" id="email" size="30" type="text" name="email" value="<?php echo $email; ?>"><br />
<label> </label><img border="0" id="captcha" src="image.php" alt=""> <a href="JavaScript: new_captcha();"><img border="0" alt="" src="images/refresh.png" align="bottom"></a><br />
<div class="field_error"><?php if($error['security_code'] != "") echo $error['security_code']; ?></div>
<label>Security Code</label><input size="13" type="text" name="security_code"><br />
<label> </label><input class="button" type="submit" name="submit" value="Submit"><br />
</form>
<?php
}
?>
</div></center>
</body>
</html>

First, we will include common.php and process.php.
In common.php, we will start the session (for the security code) and set some configuration values such as: e-mail address (where the mail should be sent), the list of errors (for each required field) that will be shown in case the form is submitted incorrectly:
common.php
<?php
error_reporting(E_ALL ^ E_NOTICE);
session_start();
header('Cache-control: private'); // IE 6 FIX
// always modified
header('Last-Modified: ' . gmdate("D, d M Y H:i:s") . ' GMT');
// HTTP/1.1
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
// HTTP/1.0
header('Pragma: no-cache');
define('IN_FORM', true);
define('MAIL_TO', 'name@your-domain.com');
$errors = array('name_enter' => 'Please enter a name.',
'subject_enter' => 'Please enter a subject.',
'message_enter' => 'Please enter a message.',
'email_enter' => 'Please enter an e-mail.',
'email_not_valid' => 'Please enter a valid e-mail address.',
'security_code' => 'The security code is incorrect. Please retype it!');
?>

The code that parses the data is in process.php. If all the fields are filled correctly, the mail will be sent. Otherwise, an array containing errors is generated, each error being shown in the form:
process.php
<?php
defined('IN_FORM') or exit;
if(!empty($_POST))
{
include_once 'functions.php';
$name = trim($_POST['name']);
$subject = trim($_POST['subject']);
$message = trim($_POST['message']);
$email = trim($_POST['email']);
$security_code = trim($_POST['security_code']);
$to_check = md5($security_code);
$error = array();
/* Name */
if(!$name)
{
$error['name'] = $errors['name_enter'];
}
/* Subject */
if(!$subject)
{
$error['subject'] = $errors['subject_enter'];
}
/* Question */
if(!$message)
{
$error['message'] = $errors['message_enter'];
}
/* E-Mail */
if(!$email)
{
$error['email']= $errors['email_enter'];
}
else if(!ValidateEmail($email))
{
$error['email'] = $errors['email_not_valid'];
}
if($to_check != $_SESSION['security_code'])
{
$error['security_code'] = $errors['security_code'];
}
// Are there any errors?
if(!empty($error))
{
$status = '<div class="notification_error">Please correct the following errors and re-submit the form.</div>';
}
else /* No Error */
{
$mail = mail(MAILT_TO, $subject, $mesaj, "From: ".$email."\r\n"."Reply-To: ".$email."\r\n"."X-Mailer: PHP/".phpversion());
if($mail)
{
$status = '<div class="notification_ok">Your message has been sent. Thank you!</div>';
}
}
}
?>
If you have any comments regarding this script, please post them! Happy coding ;-)


Do you wish to receive the latest updates as soon as they are posted? Get our RSS Feed or Subscribe to the Newsletter!
- April 30, 2009
- article by Gabriel C.
- 26 comments
Related Posts
-
AJAX Form with CAPTCHA, Realtime Validation and PHP Backendat September 2, 2008 with 534 comments
-
Basic Usage of the JS onChange() Event Handlerat November 11, 2008
-
PHP: How to validate e-mail addresses using regular expressionsat May 21, 2008 with 2 comments
-
Style your HTML Input Form Elements using CSS & JavaScriptat April 12, 2009 with 1 comment
-
How to extract domain name from an e-mail address stringat September 5, 2008

26 Replies to "PHP Contact Form with JavaScript Real Time Validation"
May 9, 2009 at 3:17 PM
[...] A PHP Contact Form with JavaScript Real Time Validation [...]
May 12, 2009 at 4:59 AM
i like this script also. a real time validation.. i can use it in my website..
keep it up! hope you can add function like, phone validation and simple credit card validation.
thx man!
May 27, 2009 at 3:16 AM
Hi, I love this contact form… I downloaded the file and I uploaded to an existing website (as it’s) but the verification numbers doesn’t work :( Can you tell me why that happens?
here is the link http://www.3nailsmedia.com/beta/form/form.php
so you can see it… maybe I’m not doing something that I should?
May 27, 2009 at 9:26 PM
Pablo,
I have accessed http://www.3nailsmedia.com/beta/form/image.php and I’ve seen an error:
Fatal error: Call to undefined function imagettftext() in /var/www/3nailsmedia.com/beta/form/class.captcha.php on line 61
To use this function you must have both the GD library and the FreeType library installed.
June 2, 2009 at 2:49 AM
Can you submit to several email addresses?
July 31, 2009 at 6:54 AM
Hi, i have a problem. I cant see the captcher picture withe the security code on my website. So tell me, what can i do?
July 31, 2009 at 7:01 AM
Send me the URL where you can’t see the captcha. I will try to figure out the issue. You need to have PHP5+, and both the GD and the TrueType libraries enabled in order to see the verification image.
August 19, 2009 at 6:59 AM
HI! What can I make if I can’t install GD library and the FreeType library. Don’t you have a version which works without these?
please help
November 5, 2009 at 2:19 AM
Hi Guys,
I have installed the form, the captcha image displays correctly but when i type in the code i keep getting an error, i’ve tried about 50 different codes but stil get the error. my form is at:-
http://www.web9.co.za/request-quotation/
if you want to see my phpinfo you can visit:-
http://web9.co.za/info/
Thank you so much, this is such a beautiful form otherwise!
November 5, 2009 at 2:46 AM
Hi Guys,
I installed the form but keep getting an error even if i type the correct captcha code.
PLEASE HELP, my form is at http://www.web9.co.za/request-quotation/
phpinfo is at
http://web9.co.za/info/
November 5, 2009 at 5:23 AM
I got it to work!
Simply turned Register_Globals to Off and voila !
November 15, 2009 at 11:07 PM
I keep getting the message:
“The security code is incorrect. Please retype it!”, but the code is typed correctly. I have slotted it into a Joomla site. Any help would be greatly appreciated.
November 17, 2009 at 3:16 AM
try turning Register_Globals Off
April 6, 2011 at 11:35 PM
Hi Shingi,
I have downloaded the files and tried it but it’s not working.
How to turn “Register_Globals Off” ?
If you don’t mine…can you please send the complete folder with all the files to my mail id at pokettankers@gmail.com
I’m very thankful to you if you would send to mail.
Thanks and Regards:
Krishna
November 18, 2009 at 5:38 PM
thanks.. i have been looking everywhere for something like this. i really don’t like validation…
November 25, 2009 at 7:16 AM
I can’t get the captcha image to display. I’m on Bluehost with PHP5, GD and Freetype installed. What am I doing wrong?
Mike Manor Music
User: admin
Pass: monkey
Click the ‘Contact’ link.
December 8, 2009 at 3:04 AM
helo I have borblem for The security code is incorrect. Please I need helpp
December 25, 2009 at 10:04 PM
How do you turn Register_Globals Off?
I cannot find it, is it a server config situation or what. I am using a hosting company and I thing they have all the requirements you listed php5 etc.
Please help
February 13, 2010 at 5:20 PM
eregi_replace has been deprecated, could do with ann update ;)
April 13, 2010 at 9:39 AM
mi web es http://www.buscopalma.es y lamento no entender la esplicacion en ingles, no obstante intentare hacer funcionar el codigo. gracias
September 7, 2010 at 3:12 AM
someone managed to solve the problem of validation captacha?. I’ve tried several codes and nothing!
October 11, 2010 at 7:47 AM
Hi hello
I want to know this PHP script is 100% free ?. I saw do you have a new one, but this seems to fit on a project I am working. But I wanna know if this script is 100% free.
Thanks!
October 13, 2010 at 5:47 AM
@Manuel: Yes, this script is 100% free. You can use it on your project. You can checkout a better script here though: http://bit.ly/c1GR5h
January 6, 2011 at 11:45 PM
Hi I was wondering why the name wont be sent. Everything works fine. Just the name of the person is missing. Any suggestions?
January 12, 2011 at 1:26 AM
Hmm, okay since nobody knows I have to use another script. Sadly I can´t wait any longer for an answer because my work is getting delayed. Nice script anyway bye.
January 30, 2011 at 6:41 PM
I keep getting the message:
“The security code is incorrect. Please retype it!”, but the code is typed correctly. Many people have the same issue i think — anybody can help us plsss