A PHP validation function

See more about:

Where are we?

You know how to do some validation. You know what a PHP function is. Let’s put them together, and create a PHP validation function.

This lesson’s goals

By the end of this lesson, you should:

  • Be able to write a PHP validation function.
  • Be able to call it.

Two products

Suppose we have two products. Here is a form:

Form

Figure 1. Form

As usual, the user enters the number of each product s/he wants, and clicks the button.

With the data in Figure 1, the user would get:

Output

Figure 2. Output

But what if the user typed this?

Form with bad data

Figure 3. Form with bad data

S/he would see:

Error report

Figure 4. Error report

Notice that each product has its own error line.

You can try the program. You can also download the files.

Repeating the validation tests

The same tests apply to both fields. For example:

  • The value should be a number.
  • The number should not be less than zero.

We could have separate code to test each field. But that would duplicate work. Instead, let’s use the same function to test both fields.

Here’s the function:

//Check the number ordered.
//Input:
//  $number_ordered: The number the user wants.
//  $number_on_hand: The number in inventory.
//Returns:
//  An error message, or an empty string if there was no error.
function check_number_ordered($number_ordered, $number_on_hand) {
  if ( $number_ordered == '' ) {
    return 'Please enter the number you want to order.';
  }
  else if ( ! is_numeric($number_ordered) ) {
    return 'Please enter a valid number.';
  }
  else if ( $number_ordered <= 0 ) {
    return 'Please enter a positive number.';
  }
  else if ( $number_ordered > $number_on_hand ) {
    return 'Sorry, we don\'t have that many in stock.';
  }
  return '';
}

Figure 5. Validation function

The comments from lines 1 to 6 explain what the function does and how to use it. They describe the parameters going into the function, and the return value that comes out.

We need two pieces of information to check whether the number ordered is valid. First, we need the number ordered. We can do most of the checks just with that. But we also need to know the number on hand, for one of the checks. That’s why the function has two parameters.

There are four if statements, each one checking for a different error. Let’s look at the first one.

if ( $number_ordered == '' ) {
   return 'Please enter the number you want to order.';
}

If $number_ordered is empty, the function ends immediately, sending back a message describing the error. It doesn’t get beyond line 9. Otherwise, the next if statement runs.

If there are no errors, none of the returns in the if statements will be run. So what do we do? The last line of the function is:

return '';

If the program gets to this point, none of the if statements has been true (because otherwise one of them would have exited the function already). That means there are no errors; the data is valid. The function returns an empty string, to show that there were no errors.

We could have done something else to show there were no errors. For example, we could have returned “NO ERRORS!” Returning an empty string is common practice, but not the only choice.

Let’s see how the function is used.

Calling the validation function

Here’s the code, with some less interesting stuff omitted:

<h1>Order Processing</h1>
<?php
//Get the input.
$frisbees = $_POST['frisbees'];
$giant_chew_ropes = $_POST['giant_chew_ropes'];
//Validate input.
$error_message_frisbees = check_number_ordered($frisbees, 15);
if ( $error_message_frisbees != '' ) {
  print "<p>Frisbees: $error_message_frisbees";
}
$error_message_giant_chew_ropes = check_number_ordered($giant_chew_ropes, 10);
if ( $error_message_giant_chew_ropes != '' ) {
  print "<p>Giant chew ropes: $error_message_giant_chew_ropes";
}
//Any error made?
if ( $error_message_frisbees != '' || $error_message_giant_chew_ropes != '') {
  print '<p>Please click the Back button on your browser and try again.</p>';
}
else {
  //Input OK, show the order.
  //Compute total.
  $frisbees_total = $frisbees * 8.95;
  $giant_chew_ropes_total = $giant_chew_ropes * 12.95;
  $order_total = $frisbees_total + $giant_chew_ropes_total;
  //Output.
  ?>
  <p>Thank you for your order.</p>
  ...

Figure 6. Calling the function

Line 14 is:

$error_message_frisbees = check_number_ordered($frisbees, 15);

This calls the function for the frisbees, and puts the return value in $error_message_frisbees. Line 18 is:

$error_message_giant_chew_ropes = check_number_ordered($giant_chew_ropes, 10);

This does the same thing for giant chew ropes. It puts the function’s return value in a different variable, $error_message_giant_chew_ropes.

As you can see, we’ve used the same validation function both times. If we had, say, 23 products on the page, we’d call check_number_ordered() 23 times. But we’d only write it once. If we needed to change the code, we’d only need to change one thing, and all the checks on the page would change.

Here are lines 15 to 17 in Figure 6:

if ( $error_message_frisbees != '' ) {
   print "<p>Frisbees: $error_message_frisbees";
}

This checks to see what the function sent back for frisbees. If it sent back an empty string (''), there was no error. If the function sent back something else, there was an error. Line 16 shows it.

The same check is done for $error_message_giant_chew_ropes is lines 18 to 21.

Now, if there was an error, any error at all, we want to ask the user to go back to the order page. It doesn’t matter which field the error was in. Could be with frisbees, or giant ropes, or both.

Look at lines 23 to 25:

if ( $error_message_frisbees != '' || $error_message_giant_chew_ropes != '') {
   print '<p>Please click the Back button on your browser and try again.</p>';
}

Line 23 says “if $error_message_frisbee is not empty, or $error_message_giant_chew_ropes is not empty, then ask the user to go back.”

This is what we want. If there is any error at all, go back to the order page. We only show the order output if there were no errors.

Summary

You learned:

  • How to write a PHP validation function.
  • How to call it.

What now?

All of our examples use two pages:

  • An HTML page with a form for input.
  • A PHP page to validate and process the data.

Webers often use one page for both input and server-side validation. Let’s see how that’s done.


How to...

Lessons

User login

Log in problems? Try here


Dogs