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>&nbsp;</label><img border="0" id="captcha" src="image.php" alt="">&nbsp;<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>&nbsp;</label><input class="button" type="submit" name="submit" value="Submit"><br />

</form>

<?php
}
?>

</div></center>

 </body>
</html>

contact-form

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!');
?>

contact-form-submit-with-errors

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!

Get our RSS Feed!

26 Replies to "PHP Contact Form with JavaScript Real Time Validation"

  1. [...] A PHP Contact Form with JavaScript Real Time Validation [...]

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

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

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

  4. Can you submit to several email addresses?

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

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

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

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

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

  9. I got it to work!

    Simply turned Register_Globals to Off and voila !

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

    1. try turning Register_Globals Off

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

  11. thanks.. i have been looking everywhere for something like this. i really don’t like validation…

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

  13. helo I have borblem for The security code is incorrect. Please I need helpp

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

  15. eregi_replace has been deprecated, could do with ann update ;)

  16. mi web es http://www.buscopalma.es y lamento no entender la esplicacion en ingles, no obstante intentare hacer funcionar el codigo. gracias

  17. someone managed to solve the problem of validation captacha?. I’ve tried several codes and nothing!

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

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

  19. Hi I was wondering why the name wont be sent. Everything works fine. Just the name of the person is missing. Any suggestions?

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

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

Leave a Reply


* = required fields

  (will not be published)


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

Note: If you want to post CODE Snippets, please make them postable first!
(e.g. <br /> should be converted to &lt;br /&gt;)