How to Validate a Form Using PHP Part 1: Complete with Error Messages!
Having a site visitor fill out a form is the primary way to gather information. Forms are the main line of communication with anyone that visits your site, so taking the time to make sure users fill them out correctly is key. Using PHP, we are able to ensure that all fields are properly filled out before submission, with required adjustments being called to attention through the use of error messages.
The CSS & HTML Groundwork
Let’s start off by opening up a fresh php document and putting a form within it. I have created errorpart1.php
<html>
<head>
<title>Form validation using PHP</title>
<style type="text/css"><!--Styles--></style>
</head>
<body>
<div id="content">
<!--PHP and Form to go here-->
</div>
</body>
</html>
With the following styles applied to the form:
*{
padding:0px;
margin:0px;
}
body{
text-align:center;
font:11px "Lucida Grande",Arial,sans-serif;
}
#content{
width:300px;
text-align:left;
margin:10px;
}
.formitem{
width:100%;
padding: 6px;
font:11px "Lucida Grande",Arial,sans-serif;
}
h2{
font:18px "Helvetica",Arial,sans-serif;
}
.box{
width:100%;
padding:10px 0px 10px 5px;
margin-bottom: 8px;
font-weight:bold;
}
.green{
background-color:#95ca78;
border-bottom:solid 1px #8AA000;
}
.red{
background-color:#FDCBCA;
border-bottom:solid 1px #E8514A;
}
Next we have to construct our form, I have chosen to create a three field form, including one hidden field entitled “submitted”, which serves to check if the form has been completed.
<form action="index.php" method="POST" enctype="multipart/form-data">
<h2>Title</h2>
<input class="formitem" type="text" name="title"/>
<br/><br/>
<h2>Content</h2>
<textarea class="formitem" name ="textentry" rows="3"></textarea>
<input type="hidden" name="submitted" value="1">
<br/><br/>
<input type="submit" value="Submit"/>
</form>
Now that we’ve laid out and styled up our page, it’s time to come in with some PHP.
The PHP and Validation
First we’ll use the hidden field (”submitted”) that we created earlier to check if the form is ready to be validated aka if they submitted it. We can do this with a simple IF statement, checking to see if submitted has a value of “1″, which it it automatically set to on form submission. This prevents error messages from popping up unless the form was actually completed and turned in.
<?php
//If form was submitted
if ($_POST['submitted']==1) {
//Do something
}
?>
Next up we have to check each mandatory field for a value of some kind. I have decided that both the title and content fields are mandatory for this example. The below code checks for values in each field on the form and assigns them to a variable if they exist.
<?php
//If form was submitted
if ($_POST['submitted']==1) {
if ($_POST[title]){
$title = $_POST[title]; //If title was entered
}
if ($_POST[textentry]){
$textentry = $_POST[textentry]; //If comment was entered
}
}
Now that we have put the values retrieved from the form into variables, we can perform a check to see if any are blank. If they have all been filled out properly, a message alerts them they completed the form properly.
//If all fields present
if ($title && $textentry){
//Do something
echo "<div class=\"box green\">Form completed!</div>";
}
?>
Now for those of you that are currently questioning why I didn’t combine the last two parts into one big IF statement, hold on, it’s error message time.
At this point in the game, we want to go back to where we first assigned the $_POST variables to strings variables, appending an else to each IF statement.
if ($_POST['submitted']==1) {
$errormsg = ""; //Initialize errors
if ($_POST[title]){
$title = $_POST[title]; //If title was entered
}
else{
$errormsg = "Please enter title";
}
if ($_POST[textentry]){
$textentry = $_POST[textentry]; //If comment was entered
}
else{
if ($errormsg){ //If there is already an error, add next error
$errormsg = $errormsg . " & content";
}else{
$errormsg = "Please enter content";
}
}
}
That last section might have seemed like a lot, so let’s break it down.
First off we established the variable $errormsg, which will contain a string with all the errors we come across.
$errormsg = ""; //Initialize errors
Next we append the first IF statement for the title field, stating that if there is no value, set the $errormsg to store that error.
else{
$errormsg = "Please enter title";
}
When we check the next field, textentry, we will essentially be doing the same thing, although this time we must check if $errormsg has any errors stored from the previous IF. Should this be the case, we must append our current error message to the previous one.
else{
if ($errormsg){ //If there is already an error, add next error
$errormsg = $errormsg . " & content";
}else{
$errormsg = "Please enter content";
}
}
At this point your $errormsg variable should have an accurate list of error messages stored. Now it is time to alert the user of any problems.
if ($errormsg){ //If any errors display them
echo "<div class=\"box red\">$errormsg</div>";
}
And that’s it. You’ve created a basic form validation/alert system, good work. There are a number of other tweaks that can be added to a form validation script, so be sure to stay tuned for Part 2.






12 Responses to “How to Validate a Form Using PHP Part 1: Complete with Error Messages!”
December 4th, 2008 at 12:21 PM
Great stuff!
December 5th, 2008 at 2:54 AM
Great post, although I do things slightly differently.
I generally add the error messages to an array, and then implode() them later on. I find it’s easier to use when you want to change the output format of the error messages.
My two cents, for what its worth
December 5th, 2008 at 4:18 AM
” if ($_POST['submitted']==1) { ”
Hm… This is a bad practice. What about notice if $_POST['submitted'] is not isset.
Try this: “if ( isset($_POST['submitted']) && $_POST['submitted']==1) { “
December 5th, 2008 at 8:24 PM
Hmm, Lekz has a point.
Either way, some great stuff Sam. I can’t wait to validate a form using PHP complete with error messages for my website.
December 5th, 2008 at 10:47 PM
As Lekz said you can check that the form has been submitted. Because of this, you really shouldn’t even need the hidden input in your html. You could simply the first if statement down to “
if ($_POST['submit']) {“. Other than that, nice tut!December 11th, 2008 at 4:56 AM
what about other types of field validation?
hope u can provide some more example ..
December 11th, 2008 at 6:16 PM
Thanks for the input everyone, you might be interested in the follow up to this article Streamline Using Arrays
January 29th, 2009 at 10:39 AM
Hey, i am sorry but this Tut ist that good.
if ($_POST['title']) will ALWAYS return TRUE. You send it via POST, and fields form a POST Form are always sent. You have to check if( ! empty($_POST['title']) ) { … }
January 29th, 2009 at 11:46 AM
@gene
I’m sorry you feel that way.
Although your method works too, you are mistaken on the POST always returning true, if what you said was the case, my demo would not display error messages, which it does. It’s a different approach.
I would encourage you to check out my Part 2, maybe that will be more to your liking
April 30th, 2009 at 9:03 AM
Your demo doesn’t work
http://www.buildinternet.com/live/errorpart1.php
If I enter title and submit, the typed content in title vanishes which shouldn’t happen……..
April 30th, 2009 at 10:09 AM
@yogi
The demo actually works as intended. If you look at my following Part 2 tutorial, I go over how to fix this.
Join the Conversation!