3.6. Validating Data and Presenting Errors

Right now, the only error handling we've seen is on the "Post Dts" field, thanks to the formatter. We want to make some of our fields required and potentially check for other issues. PHOCOA has a built-in data normalization and validation mechanism.

It's time once again to introduce another concept: Key-Value Validation. The Key-Value Validation mechanism looks for specially-named functions of your class, with the following prototype:

boolean validate<Key>(&$value, &$edited, &$errors)

It is very important to notice the pass-by-reference used on all three parameters.

So, we can implement our two validators by adding the following code to our model object Blog in Blog.php:

    function validateTitle(&$value, &$edited, &$errors)
    {
        $value = trim($value);
        $edited = true;
        $ok = true;
        if (!$value)
        {
            $errors[] = new WFError("The blog post must have a title.");
            $ok = false;
        }
        if (strlen($value) > 20)
        {   
            $errors[] = new WFError("The blog post title must be 20 characters or less.");
            $ok = false;
        }
        return $ok;
    }
    
    function validatePostDts(&$value, &$edited, &$errors)
    {   
        if (!$value and !$this->isNew())
        {   
            $errors[] = new WFError("You must enter the Posting date.");
            return false;
        }
        return true;
    }

    function validatePost(&$value, &$edited, &$errors)
    {
        $value = trim($value);
        if (!$value)
        {
            $errors[] = new WFError("You have not entered your blog post!");
            return false;
        }
        return true;
    }

Validators in PHOCOA are a bit different than some validation mechanisms. Validators are called BEFORE the actual value is set, by the Bindings system, as a pre-flight mechanism. Doing it this way prevents invalid data from ever being in the class.

The validators can also do normalization of the data. Since the value is passed by reference, you can normalize the data in any appropriate way. If you do alter the data, be sure to set edited to true.

Notice also that the errors parameter is an array. This allows you to specify multiple errors during validation.

If you look now in edit.tpl, you can see how we display errors in PHOCOA. The tag {WFShowErrors} will display all errors. By adding an id attribute to the tag, it will show just the errors associated with that UI element. You will see this done next to the individual widgets.

Now try the form again, but this time enter invalid data for the title (blank, or more than 20 chars) and date (blank) fields. You'll see that all of the errors are listed above the form, and the specific errors are again repeated next to the relevant form elements.