PHP

Validating numeric fields

Checking that values are numeric, are within a range, or have the correct format is another common validation task. For winestore customers, there are three numeric fields: the zip code, and the fax and telephone numbers.

We validate zip codes using a regular expression:

// Validate Zipcode
if (!ereg("^([0-9]{4,5})$", $formVars["zipcode"]))
   $errorString .=
      "The zipcode must be 4 or 5 digits in length";

This permits a zip code of either four or five digits in length; this works for both U.S. zip codes and Australian postcodes, but it's unsuitable for many other countries. Another common validation check with zip codes is to check that they match the city or state using a database table, but we don't consider this approach here.

The optional phone and fax numbers are also validated using regular expressions:

// Phone is optional, but if it is entered it must have
// correct format
$validPhoneExpr = "^([0-9]{2,3}[ ]?)?[0-9]{4}[ ]?[0-9]{4}$";
if (!empty($formVars["phone"]) &&
    !ereg($validPhoneExpr, $formVars["phone"]))
   $errorString .=
      "The phone number must be 8 digits in length, " .
      "with an optional 2 or 3 digit area code";

The if statement contains two clauses: a check as to whether the field contains data and, if that is true, a check of the contents of the field using ereg( ). As discussed in Chapter 2-as in many other programming languages-the second clause is checked only if the first clause is true when an AND (&&) expression is evaluated. If the variable is empty, the ereg( ) expression isn't evaluated.

The ereg( ) expression works as follows:

  • The expression ^([0-9]{2,3}[ ]?)? matches either zero or one occurrence of the bracketed expression at the beginning of the value. Inside the brackets, the expression that is matched is either two or three digits and an optional single space character (represented as [ ]?). For example, a string "03 " matches, as does "013 ", "03", and "013".

  • The rest of the expression [0-9]{4}[ ]?[0-9]{4}$ matches exactly four digits, followed by an optional space, followed by another four digits, and then the end of the string is expected. For example, the strings 1234 1234 and 12341234 both match the expression.

  • The entire expression matches the following classes of strings: 03 1234 1234, 013 1234 1234, 1234 1234, 0312341234, 01312341234, 03 12341234, 013 12341234, 12341234, 0131234 1234, and 031234 1234.


by BrainBellupdated
Advertisement: