Contact form of websites led user to communicate with website owners. This shows a genuine or loyal behavior of an organization towards its customers. Here we bring up in front of you the PHP contact form with validation feature.

In our previous blogs, we have applied JavaScript and jQuery codes on the contact form. Now, this tutorial emphasizes on applying PHP validations and mail() function over contact form.



Here, our PHP validation includes the following steps:

  1. Checking for empty fields.
  2. Checking for data filtration.
  3. Input comparison with Regular expression.
  • First, we used PHP empty() function to check for empty fields.


if (empty($_POST["name"]))
{
echo "Name is required";
}
  • Second, we pass the non empty value to a user defined function test_input($data) to filter user input.

// Function for filtering input values.
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}

  • Third, we applied preg_match() function to the above filtered value to get user input in correct format based on regular expression.

preg_match("/^[a-zA-Z ]*$/",$_POST['name']) // For a name or other text fields.
preg_match("/([w-]+@[w-]+.[w-]+)/",$_POST['email'])// For email field.

And at the end, we mail user input message using PHP mail () function in such a way that the sender will also get the copy of his mail.


mail("[email protected]",$msg, $header);

Watch our live demo or download our codes to use it. validation in contact form using php

Complete HTML and PHP codes are given below.

PHP file: contact_form.php

Given below our complete HTML contact form.


<?php include 'validation.php';?>
<!DOCTYPE HTML>
<html>
<head>
<title>PHP Contact Form with Validation</title>
<link rel="stylesheet" href="css/style.css" />
</head>
<body>
<div class="container">
<div class="main">
<h2>PHP Contact Form with Validation</h2>
<form method="post" action="contact_form.php">
<label>Name :</label>
<input class="input" type="text" name="name" value="">
<span class="error"><?php echo $nameError;?></span>
<label>Email :</label>
<input class="input" type="text" name="email" value="">
<span class="error"><?php echo $emailError;?></span>
<label>Purpose :</label>
<input class="input" type="text" name="purpose" value="">
<span class="error"><?php echo $purposeError;?></span>
<label>Message :</label>
<textarea name="message" val=""></textarea>
<span class="error"><?php echo $messageError;?></span>
<input class="submit" type="submit" name="submit" value="Submit">
<span class="success"><?php echo $successMessage;?></span>
</form>
</div>
</div>
</body>
</html>

PHP file: validation.php

In the below script, we validate all fields and then mail the message using PHP mail() function. Also, the sender will get the copy of his mail.


<?php // Initialize variables to null.
$name =""; // Sender Name
$email =""; // Sender's email ID
$purpose =""; // Subject of mail
$message =""; // Sender's Message
$nameError ="";
$emailError ="";
$purposeError ="";
$messageError ="";
$successMessage =""; // On submittingform below function will execute.
if(isset($_POST['submit'])) { // Checking null values in message.
if (empty($_POST["name"])){
$nameError = "Name is required";
}
else
 {
$name = test_input($_POST["name"]); // check name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name))
{
$nameError = "Only letters and white space allowed";
}
} // Checking null values inthe message.
if (empty($_POST["email"]))
{
$emailError = "Email is required";
}
else
 {
$email = test_input($_POST["email"]);
} // Checking null values inmessage.
if (empty($_POST["purpose"]))
{
$purposeError = "Purpose is required";
}
else
{
$purpose = test_input($_POST["purpose"]);
} // Checking null values inmessage.
if (empty($_POST["message"]))
{
$messageError = "Message is required";
}
else
 {
$message = test_input($_POST["message"]);
} // Checking null values inthe message.
if( !($name=='') && !($email=='') && !($purpose=='') &&!($message=='') )
{ // Checking valid email.
if (preg_match("/([w-]+@[w-]+.[w-]+)/",$email))
{
$header= $name."<". $email .">";
$headers = "FormGet.com"; /* Let's prepare the message for the e-mail */
$msg = "Hello! $name Thank you...! For Contacting Us.
Name: $name
E-mail: $email
Purpose: $purpose
Message: $message
This is a Contact Confirmation mail. We Will contact You as soon as possible.";
$msg1 = " $name Contacted Us. Hereis some information about $name.
Name: $name
E-mail: $email
Purpose: $purpose
Message: $message "; /* Send the message using mail() function */
if(mail($email, $headers, $msg ) && mail("[email protected]", $header, $msg1 ))
{
$successMessage = "Message sent successfully.......";
}
}
else
{ $emailError = "Invalid Email";
 }
 }
} // Function for filtering input values.function test_input($data)
{
$data = trim($data);
$data =stripslashes($data);
$data =htmlspecialchars($data);
return $data;
}
?>

CSS File: style.css

Styling HTML elements.


/* Below line is used for online Google font */
@import url(http://fonts.googleapis.com/css?family=Raleway);
h2
{
background-color: #FEFFED;
padding: 15px 35px;
margin: -10px -50px;
text-align:center;
border-radius: 10px 10px 0 0;
}
hr
{
margin: 10px -50px;
border: 0;
border-top: 1px solid #ccc;
}
span
{
color:red;
}
div.container
{
width: 960px;
height: 610px;
margin:35px auto;
font-family: 'Raleway', sans-serif;
}
div.main
{
width: 350px;
padding: 10px 50px 30px;
border: 2px solid gray;
border-radius: 10px;
font-family: raleway;
float:left;
}
input[type=text],textarea
{
width: 97.7%;
height: 34px;
padding-left: 5px;
margin-bottom: 5px;
margin-top: 5px;
border: 2px solid #ccc;
color: #4f4f4f;
font-size: 16px;
border-radius: 5px;
}
textarea
{
resize:none;
height:80px;
}
label
{
color: #464646;
text-shadow: 0 1px 0 #fff;
font-size: 14px;
font-weight: bold;
}
.submit
{
padding: 10px;
text-align: center;
font-size: 18px;
background: linear-gradient(#ffbc00 5%, #ffdd7f 100%);
border: 2px solid #e5a900;
color: #ffffff;
font-weight: bold;
cursor: pointer;
text-shadow: 0px 1px 0px #13506D;
width: 100%;
border-radius: 5px;
}
.submit:hover
{
background: linear-gradient(#ffdd7f 5%, #ffbc00 100%);
}


Pabbly Form Builder


Conclusion: This was all about, contact form validation in PHP. Hope you like it, keep reading our other blogs posts and do provide us your valuable feedback.