How to Validate Numbers in Web Form Fields - dummies

By Steve Suehring, Janet Valade

Validating numbers in a web form can involve a regular expression, if you’re expecting a certain format or number of digits, or can involve math if you’re looking for certain values (or could be both too).

ZIP code validation presents an easier case, so you tackle that first. You need to validate that only digits were entered into the ZIP field and that there are at least five and no more than nine digits in the field. You could do this with a single regular expression, but doing so would prevent you from returning a specific error message:

You wouldn’t know if users filled in letters or if they only had four digits in the ZIP field. Therefore, the method you in the next exercise separates those two tests into their own conditional.

This code can be added above the final disposition section:

if (isset($_POST['zip']) && $_POST['zip'] != ") {
    if (!preg_match('/^[d]+$/',$_POST['zip'])) {
        $_SESSION['error'][] = "ZIP should be digits only.";
    } else if (strlen($_POST['zip']) < 5 || strlen($_POST['zip']) > 9) {
        $_SESSION['error'][] = "ZIP should be between 5 and 9 digits";

The code first checks to see if the ZIP is set. If it is set and isn’t empty, then the next check is to see if it contains only digits. If it contains something other than digits, then there’s no need to run the next test. If digits are all that’s found, then the next check can be run, to make sure the length is between 5 and 9 digits.

Validating the phone number uses the same logic. If the phone field is set and not blank, then check to make sure it contains only digits. Next, the length is checked to make sure it’s at least ten digits. You could also add a maximum length check here, but this one will account for international numbers, too.

The phonetype field is checked next. If it isn’t set (and you know that it’s required because you’re inside of a conditional test checking whether the phone number was set), then you return an error. Assuming that it’s indeed set, check the value to make sure it’s one of the acceptable values for the field, similar to that done in the previous section for the state drop-down.

This code can be added above the final disposition section in form-process.php.

if (isset($_POST['phone']) && $_POST['phone'] != ") {
    if (!preg_match('/^[d]+$/',$_POST['phone'])) {
        $_SESSION['error'][] = "Phone number should be digits only";
    } else if (strlen($_POST['phone']) < 10) {
        $_SESSION['error'][] = "Phone number must be at least 10 digits";
    if (!isset($_POST['phonetype']) || $_POST['phonetype'] == ") {
        $_SESSION['error'][] = "Please choose a phone number type";
    } else {
        $validPhoneTypes = array("work","home");
        if (!in_array($_POST['phonetype'],$validPhoneTypes)) {
            $_SESSION['error'][] = "Please choose a valid phone number type.";