Reader
  • Home
  • About
  • Deals
  • Services
  • Contact

PHP Contact Form with JavaScript Real Time Validation

Last updated on March 25th, 2015 by Gabriel Livan

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', '[email protected]');

$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."rn"."Reply-To: ".$email."rn"."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 😉

Download   View Demo

Filed Under: JavaScript, PHP

About Me

Gabriel LivanHey, there! I'm Gabriel Livan, Web Developer, Blogger and Internet Marketer. I love making fast, secure and scalable web applications, running and travelling around the world. I blog about WordPress, site speed & security and quality tools for web professionals. Read more

What are you looking for?

Categories

  • AJAX (22)
  • Deals (10)
  • Design (30)
  • eBooks (2)
  • Flash (19)
  • Freebies (11)
  • General (62)
  • Giveaways (1)
  • Graphics (27)
  • HTML & CSS (35)
    • Frameworks (9)
  • JavaScript (160)
    • Frameworks (8)
    • jQuery (89)
    • MooTools (14)
  • Page Loading Speed (2)
  • Photoshop (3)
  • PHP (113)
  • Reviews (8)
  • SEO (6)
  • Statistics (2)
  • Web Tools (13)
  • WordPress (27)
    • Plugins (15)
    • Snippets (4)
    • Tools (2)
    • Tutorials (6)

Copyright © 2026 · BitRepository.com - All Rights Reserved

  • Home
  • About
  • Contact