When form validation fails, how to pass error information for new try?

I'm developing a form validation class in PHP. When form validation fails, I can easily redirect again to the form's html page but without error information. I would like to redirect to the form's page with the specific errors about which fields failed and why.

How should I do this? Should I send information back via GET or POST? and in which format? Would really to see some code to see how people tackled this problem.


13.10.2009 15:12:19

Something like this:

// Pseudo Code

function isValid($parm) {
   $return = false;
   if(preg_match(/^[a-zA-Z]+$/, $parm) {
      $return = true;
   return $return;

$firstname = $_GET["fname"];
$lastname  = $_GET["lname"];

$validFirstName = isValid($firstname);
$validLastName  = isValid($lastname);

if($validFirstName == true && $validLastName == true) {
   echo "It's all good";
   // Do what you need to like, Submit
} else {
   echo "Please retry";
   // Display error message
13.10.2009 15:31:49
Thanks but that is going to render information in the action page. I would like to go back to the form's page and render erros there, for each field, next to it.
Andy 13.10.2009 15:22:32
This would keep you on the same page unless validation passes, then redirect/submit/etc...
Phill Pafford 13.10.2009 15:24:04

You could use the header() function. So just check the fields that are posted:

    $msg = "Form is not valid";
} else { 
    //Don't know if you want this
    $msg = "Form is valid";

header("Location: [page where you came from]?msg=" . urlencode($msg));

Then in the page where you're redirecting to use

    echo urldecode($_GET['msg']);

to echo the message. If you are using other get variables in the location of the header function, of course, use &msg=" . urlencode($msg). (You may also want to return the values that the user submitted, so the user doesn't have to fill out the entire form again if he makes 1 mistake.

13.10.2009 15:23:30

there are number of approaches

  • pass errors in GET when redirecting back like you said
  • use sessions to store error info, on the form page check Session for errors
  • do not redirect after failure, just output form again along with error messages
  • ajax submits

which one to use depends on the application. For most apps sessions method is most appropriate.

13.10.2009 15:25:22

I agree with user187291's suggestion of using $_SESSION because:

  • It doesn't hijack the URI like using $_GET (you would never want a static link to a status message). Users could press "back" to the page with your form and still see a status message because the URI says so.
  • Print and unset it in the same run, you won't be able to use it more than once (which is what you want?!)

If you're going with AJAX, $_GET is more widely used for retreiving values, which you are doing from the validation controller.

7.10.2011 18:13:01
If you agree with it, how come it has zero upvotes at this time?
Sam 12.04.2011 08:29:15
@Sam: Well, I partly agree with it but not with "do not redirect after failure, just output form again along with error messages" since that would cause the back button to hang up. Feel free to upvote it yourself, by all means :) Btw, your website is unavailable!
chelmertz 12.04.2011 19:16:54
Thanks for pointing it out, I must have forgotten that I changed the url to be less redundant at some point
Sam 12.04.2011 19:43:37

I use a class to interface with $_POST, similar to the following:

// create the object
$post = new PostData();

// register your requirements... write whatever methods you need
// for each call,read $_POST, check criteria, and mark the field
// as good or bad...
$post->required ('LastName');
$post->required ('FirstName');
$post->numeric ('Age');
$post->optional ('MiddleInitial');
$post->regExp ('/\d{3}/','AreaCode');
$post->email ('Email');

// check the status
if (!$post->isValid ())
    $_SESSION['FailedPostData'] = $post;
    header ('Location: page.php');

// normal form processing

Then, on page.php, you can see if FailedPostData is in the session, read it to find the info entered last time, as well as which fields that failed. I use a template engine with macros that let me easily re-populate the form inputs and mark the failures. Otherwise you might end up with lots of code for a simple form...

You'll also need a mechanism to be sure that stale FailedPostData doesn't hang around in the session and confuse things.

18.10.2009 16:50:00

I am doing it this way. Beginner in php so not sure if this is the best way to do:

HTML Form Page:

<form id="abc" method="post" action="validate.php">

PHP Page ..validation conditions..call a function if things do not match

function display_error($error) {
        echo "<html><body><link href='style.css' rel='stylesheet' type='text/css'><br><center><h2>";
        echo "$error";
        echo "</h2></center><br><br>";
        echo "<center><input type='button' value='Go Back' onClick='history.go(-1)' style='width:100px; height:28px; font-size:16px'></center>";
        echo "</body></html>";

Clicking on the back button takes you back to the html page with the data intact.

14.07.2014 22:16:41