Form Validation

Validation is all about checking that user input conforms to a set of rules. It is possible for us to write Javascript code to trap user errors and prevent invalid data from ever being received by a PHP script. We can also stick entirely with our PHP and achieve everything we might need to.

Presence Check

The most basic check is to see if a user has supplied information where it is expected. Some text fields might be optional in a form, some required. The following statements check that an entry has been made,

if (!strlen($_POST['surname'])
{
   echo "<p>You must enter something in the surname field.</p>";
}

Type Check - Numeric

You can check for numeric information in a couple of ways. To check for positive integers, use the following,

if (!ctype_digit($_POST['stuff']))
{
   echo "<p>Stuff must be numeric.</p>";
}

To allow negative integers to be included, tweak the statement,

if ($_POST['stuff']!=strval(intval($_POST['stuff'])))
{
   echo "<p>Stuff must be numeric.</p>";
}

For floating point numbers, a little change is needed,

if ($_POST['stuff']!=strval(floatval($_POST['stuff'])))
{
   echo "<p>Stuff must be numeric.</p>";
}

There is an isnumeric() function in PHP. Be careful though, there are lots of ways to write valid numbers. Some letters are used in some of these representations.

Format Check

We can perform a format check using regular expressions. There is a Comp 3 page with some information about how to form a pattern for a regular expression. Further details can be found in the PHP documentation.

$pattern = '/[+\-]?\d+/';
$num = "-34";
if (!preg_match($pattern, $num))
{
   echo "<p>1 Not an integer.</p>";
}

Dates & Times

Presence, time and format checks aren't enough to ensure that a date is valid. Firstly, a date needs to be an actual date - the right number of days in the month, a month number that actually represents a month and so on. It might be that the selected date needs to be later in time than the current date, before a particular moment in time, within a week of a specific date, a working day or pretty much any constraint you can consider. In such cases, you need to do multiple checks on the information your script has received.

Closed & Open Questions

You can limit the opportunity for invalid data by considering the user interface. Dropdown boxes, check boxes, radio buttons can all have a default selection and a strictly limited number of choices. Designed well, there is little opportunity for invalid data to creep in. Lots of web-based applications make use of this method.

Do remember that an A2 project has to showcase your skills. There is an expectation that a program will validate user input and that error messages are delivered to the user explaining the problem. You are advised to have some good examples of validation routines in your programs.