Build Internet has a brand new theme, and that's only the beginning. Read the full story or hide this bar

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.

Wordpress.com stats not installed! Posted Tuesday, December 2nd, 2008 / Back to Top

I this post. Tweet
SPONSOR

26 Comments 3 Mentions

  1. Paul Davis Author Editor

    Great stuff!

    December 4, 2008 · Reply

  2. Geoff Author Editor

    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 5, 2008 · Reply

  3. Lekz Author Editor

    ” 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 5, 2008 · Reply

  4. Mitch Author Editor

    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 5, 2008 · Reply

  5. Will Wilkins Author Editor

    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 5, 2008 · Reply

  6. rania Author Editor

    what about other types of field validation?
    hope u can provide some more example ..

    December 11, 2008 · Reply

  7. Sam Dunn Author Editor

    Thanks for the input everyone, you might be interested in the follow up to this article Streamline Using Arrays

    December 11, 2008 · Reply

  8. gene Author Editor

    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 29, 2009 · Reply

  9. Sam Dunn Author Editor

    @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

    January 29, 2009 · Reply

  10. yogi Author Editor

    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 30, 2009 · Reply

  11. Sam Dunn Author Editor

    @yogi
    The demo actually works as intended. If you look at my following Part 2 tutorial, I go over how to fix this.

    April 30, 2009 · Reply

  12. qistina Author Editor

    Great info
    .-= qistina´s last blog ..Mi Goreng Tom Yam =-.

    September 10, 2009 · Reply

  13. kaise Author Editor

    Hi,

    I was wondering if anybody has a tutorial to create a cms from scrtach.

    I wish to learn and i’m a newbie. any help will be much appreciated.

    my email is –
    kaise@hotmail.co.uk

    Thanks

    November 17, 2009 · Reply

  14. zoma Author Editor

    Hi,

    Great tutorial

    Thanks a lot….!!!!! :)

    January 1, 2010 · Reply

  15. 249 Designs Author Editor

    Great tut. Part 2 will help clear up some problems – I’m sure.

    June 23, 2010 · Reply

  16. Dave Author Editor

    Hey guys,

    Can anyone help me out – I’ve tried implementing this in to a simple contact form I’m making and it doesn’t seem to do anything?! I’ve been trying for quite a while with several different form validation techniques and none of them seem to work.

    Is anyone able to offer some advice…?

    http://jappdesign.co.uk/contact_test.php

    Thanks in advance!

    Dave

    July 11, 2011 · Reply

  17. kensar Author Editor

    Very helpful.

    I have been looking for such this kind of article.

    Please keep your good work.

    July 13, 2011 · Reply

  18. Vikas Author Editor

    nice one help me to do work

    August 10, 2011 · Reply

  19. byterbit Author Editor

    also cant get it to do anything; perhaps a complete code listing on one entity would be helpful ?

    August 11, 2011 · Reply

  20. Tedy Author Editor

    Hellow. Nice tut dude.

    how about validating forms when you have to check whether the form contains only alphanumeric characters or not ? or checking if the password field matches the confirm password field, etc.

    October 23, 2011 · Reply

  21. Jonas Lagerwall Author Editor

    I wrote a form validator in case someone wants to check it out. The approach is slightly different from what is used here. It can be found on jform.lagerwall.net.

    Cheers!

    January 3, 2012 · Reply

  22. ola Author Editor

    Pls what can be wrong??i have the following data and i want to input them into mysql database but its not inputing..what might be wrong??the code goes below:

    January 4, 2012 · Reply

  23. ola Author Editor

    ()

    January 4, 2012 · Reply

  24. ola Author Editor

    include”config.php”;

    $username = $_POST['uname'];
    $firstname = $_POST['fname'];
    $lastname = $_POST['lname'];
    $email = $_POST['email'];
    $password = md5($_POST['pswd']);
    $confirmpassword = md5($_POST['confpswd']);
    $phone = $_POST['phone'];
    $dateofbirth = $_POST['dob'];
    $address = $_POST['address'];
    $city = $_POST['city'];
    $state = $_POST['state'];
    $postcode = $_POST['code'];
    $country = $_POST['country'];

    $insert = ‘INSERT INTO user_reg(id, uname, fname, lname, email, pswd, confpswd, phone, dob, address, city, state, code, country)
    VALUES (“‘.$username.’”, “‘.$firstname.’”, “‘.$lastname.’”, “‘.$email.’”; “‘.$password.’”; “‘.$confirmpassword.’”; “‘.$phone.’”;
    “‘.$dateofbirth.’”; “‘.$address.’”; “‘.$city.’”; “‘.$state.’”; “‘.$postcode.’”; “‘.$country.’”)’;

    mysql_query($insert);

    January 4, 2012 · Reply

  25. siva Author Editor

    hi..great one

    January 11, 2012 · Reply

  26. Don Author Editor

    Great post, hope we can learn from each others, hope to learn more about PHP

    January 18, 2012 · Reply

 

Join the Conversation

Back to Top / Comment RSS

2011 Build Internet. Created by One Mighty Roar. Icons by Komodo Media. Back to Top