Same page validation

Tags
Summary

Put a form and its validation code on the same page.

Situation

You have a form. For example:

Form

You want to validate the data, before processing it. If there data is bad, show an error message, and the form again, with the data the user entered:

Error message

Provides

Validated user input data, ready for processing.

Action

Put a form and its validation code on the same page.

Here's how it works:

Process

User comes to the page for the first time

$userInput is set to MT (1). There is no POST data (2), so skip that bit. There are no errors, since there is no data to check (3), so skip that as well. Show the widget (4). $userInput is MT, so the widget will be MT.

We end up with what we wanted.

Form

User entered data and pressed submit button

Data flow

The use types some data, and hits the button. The page sends the data to itself.

$userInput is set to MT (1), as before. There is POST data (2) this time. Put the user's data into $userInput. Validate it. If it's OK, when send the data off for processing.

If the data isn't valid, the program continues. Show errors from validation (3). Show the widget, with $userInput in it (4). Recall that $userInput has the data the user typed in last time.

We have what we wanted:

Error message

Where referenced