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

With the following styles applied to the form:

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

Posted Tuesday, December 2nd, 2008 · Back to Top

SPONSOR

Add Comment

59 Comments 3 Mentions

  1. Paul Davis Author Editor

    Great stuff!

    ·

  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 :)

    ·

  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) { “

    ·

    • Ana Author Editor

      Very good point, thanks!

      ·

  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.

    ·

  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!

    ·

    • Balint Author Editor

      Checking $_POST['submitted']==1 is actually a great thing if you have more submit buttons in a form. This way you can check which one of them were pressed. For example imagine a form with a file upload option. If the user presses the submit button next to the file upload element, it uploads the file to the server then displays it in the form. But if the user presses the second submit button under the whole form, all input fields are verified and then and only then is the data and image parameters written to the database and the image is copied from the temp folder to another folder.
      I have to notice that by temp folder I don’t mean the tmp folder php uses. After uploading a file, you have to copy it to a “safe” folder where it is guaranteed that the file will stay there, which is not true in case of the tmp folder.

      ·

      • TWZOP Author Editor

        In that case, you would give each button a different name and refer to it in the $_POST['buttonname'] array and still not need to specify a hidden field.

        ·

  6. rania Author Editor

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

    ·

  7. Sam Dunn Author Editor

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

    ·

  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']) ) { … }

    ·

  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

    ·

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

    ·

  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.

    ·

    • TWZOP Author Editor

      We all have different methods for doing things. Your way works just as many other ways. Thanks for taking the time to do the tut. I appreciate what you’ve done. Great work.

      ·

  12. qistina Author Editor

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

    ·

  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

    ·

  14. zoma Author Editor

    Hi,

    Great tutorial

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

    ·

  15. 249 Designs Author Editor

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

    ·

  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

    ·

  17. kensar Author Editor

    Very helpful.

    I have been looking for such this kind of article.

    Please keep your good work.

    ·

  18. Vikas Author Editor

    nice one help me to do work

    ·

  19. byterbit Author Editor

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

    ·

  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.

    ·

    • TWZOP Author Editor

      You need to look at using regular expressions to accomplish that.

      You may want to look at: http://bit.ly/UxZaWp

      ·

  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!

    ·

  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:

    ·

  23. ola Author Editor

    ()

    ·

  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);

    ·

    • pradip Author Editor

      it’s a very useful for me as a beginer level..

      ·

    • raj Author Editor

      I also follow this way..

      ·

  25. siva Author Editor

    hi..great one

    ·

  26. Don Author Editor

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

    ·

  27. prices gate Author Editor

    Great write-up, I’m normal visitor of one’s website, maintain up the nice operate, and It is going to be a regular visitor for a lengthy time.

    ·

  28. pihrevren Author Editor

    [url=http://nirwedr3d.springnote.com/pages/11067072]buy discount free prescription diazepam invent [/url]
    [url=http://cialis3e4r.fashionsdiary.com/uncategorized/cialis-same-day-delivery.html]cialis same day delivery[/url]
    [url=http://cialis3e4r.fashionsdiary.com/uncategorized/buy-cialis-overnight.html]buy cialis overnight[/url]
    [url=http://www.magentoupgrade.com/magento-commerce-tutorials/amoxicillin-no-prescription-needed.html]buy cash delivery Amoxicillin Brakebill [/url]
    [url=http://deraste3w.springnote.com/pages/11067752]zithromax fekine values [/url]
    [url=http://answer.howtocooks.com/buy-viagra-online-overnight-fedex-delviery.html]purchase viagra online without prescription handout [/url]
    [url=http://www.magentoupgrade.com/magento-commerce-tutorials/order-accutane-no-prescription.html]cheap Accutane delivery fedex childhealthhrb [/url]
    [url=http://www.findcaranswer.com/?p=5815]ultram cheap next day assertiveness [/url]
    [url=http://www.findcaranswer.com/?p=5816]cheapest online ambien mummys [/url]
    [url=http://answer.howtocooks.com/soma-without-prescription-overnight-delivery.html]soma pharmacy COD saturday delivery CONTRACTOR [/url]
    [url=http://nirwedr3d.springnote.com/pages/11067076]buy carisoprodol online overnight eager [/url]
    [url=http://www.findcaranswer.com/?p=5813]soma order Rockport [/url]
    [url=http://answer.howtocooks.com/tramadol-overnight-cod.html]cheap discount tramadol calif [/url]
    [url=http://deraste3w.springnote.com/pages/11067716]cheap order Valtrex LinksBerisi [/url]

    ·

  29. hapsari Author Editor

    nice post :)

    ·

  30. party supplies Author Editor

    brilliant. could i point one of my articles to this as im writing one on a similar topic. thanks..

    ·

  31. charlie Author Editor

    I don’t know if I’m doing something wrong or if this isn’t working. I placed all the above code (html and php) into one php file and tried submitting it to another blank php file, and when I didn’t fill in a form value, the form would still submit and transfer me to the php page.

    I’m a bit confused how PHP can even be used to validate forms before submission in the first place. PHP is all server side and submission is done client side. The only time anyone has time to validate (unless using jquery) is on the server side right after submission, but by then it’ll be too late. You’ll already have submitted and so you can’t show an interactive message that there’s something wrong.

    I think the better solution is to just use jquery but I hate how much of a headache it is so I was trying not to use it.

    ·

  32. Aliervelype Author Editor

    a solid offer of the classic time, [url=http://www.lv-japan.net/]ルイヴィトン[/url] bogus Louis Vuitton affordable handbags deserted consideration most people individually them over too record when it comes to round out piece.These same louis vuitton school bags go shopping environment wayEurope’password strength most well-known [url=http://www.lv-japan.net/]ルイビトン 財布[/url] supplier are families small business progression through, the person was slain between one generation to another, low-key and stylish, and each and every name brand the excellent personality traits with observe your self. ルイビトン 財布 : http://www.lv-japan.net/

    ·

  33. stark Author Editor

    hi guys can u help me with how to check for the type of a data sent by a textfield? when ever i use the gettype() it always returns String

    ·

  34. stark Author Editor

    email: e.anim48@yahoo.com

    ·

  35. Nil Author Editor

    thanks for this tutorial…:)
    I have placed my form inside “echo” similar to this
    switch(ch)
    {
    case 1:
    echo”
    ………
    ………
    ………
    …….

    }

    the evaluate.php is given as below:———-

    The ERROR that they are giving:-
    Notice: Undefined index:check

    I am a beginner in php………….plz help waiting for ur reply……

    ·

  36. Echo Author Editor

    I believe (please correct if I’m wrong) the better way of checking wheter or not has been submitted is to check the request method like this:

    if($_SERVER['REQUEST_METHOD'] == “POST”)

    ·

  37. Echo Author Editor

    Another point, I think it will be better to initialize the $errors var as an array, so something like the following

    if ($_SERVER['REQUEST_METHO'] == “POST”){

    # Initialize the errors array
    $errors = array();

    # Check if the variable was submitted

    if ($_POST['fname']){
    $fname = $_POST['fname'];
    }
    else {
    $errors [] = ‘Please enter your First Name’;
    }
    …………

    ·

  38. Fabro Author Editor

    Thanks for it, it helped me a lot. :)

    Just a comment…

    This line:

    should be:

    Right?

    ·

  39. Randika Author Editor

    Hi Sam, this is a great piece of knowledge for beginners., keep up all the good work..:)

    ·

  40. Zuhaib Shah Author Editor

    Very nice you are great love u

    ·

  41. Bright Author Editor

    Very Kool

    ·

  42. Adam D Author Editor

    Is it just me or is this form missing any sort of security?
    It wouldn’t be hard to post an XSS cookie stealer and leech the admins login session.

    ·

  43. Babrak Author Editor

    hi dears…
    i have a problem when ever i entered ” or ‘ in my name text box they give error message…

    ·

  44. Mo Danish Author Editor

    Look Here and get The Orignal code to simple read.

    ·

  45. cheap christian louboutin Author Editor

    I would like to suggest you that traffic show most people read blogs on Mondays. So it should encourage blogger to write new write ups over the weekend primarily.

    ·

  46. pay day lenders Author Editor

    Do you have a spam issue on this website; I also am a blogger,
    and I was wanting to know your situation; we have created some nice procedures and we are looking to trade solutions with
    others, why not shoot me an e-mail if interested.

    ·

  47. Ana Author Editor

    Great tutorial!
    Thank you so much!

    ·

  48. fgh Author Editor

    dfgchj

    ·

  49. Crossfit Workouts Author Editor

    Wow that was strange. I just wrote an incredibly long comment but after I clicked submit my comment didn’t appear.
    Grrrr… well I’m not writing all that over again. Anyways, just wanted to say superb blog!

    ·

  50. Nannette Author Editor

    Rest assured initially when i first tried reading this article
    I failed to visualise the situation turned out quite probable that those things you dealt with on this page perhaps even
    existed.

    ·

  51. jithin Author Editor

    nice..

    ·

 

Build Internet by One Mighty Roar. Since 2008.