9.8. Validation

The first rule of development is never trust data from your users (no offense, users). The ORM layer provides a handy means to hook into the Zend_Validate API and make your entities validate the information going into them.

9.8.1. Options

Before we dive head-first into creating validation rules for the fields on your entity, let's explain the options available for the validation system.

You can turn validation off for an entity. It's on by default. Simply call the disableValidation method on the entity type object.

<?php
/* @var $mapper PersonMapper */
$type = $mapper->getEntityType('Person');
$type->disableValidation();

You can also specify whether validation occurs after each property is set or right before the entity is saved. By default, values are validated as they are set.

<?php
/* @var $mapper PersonMapper */
$type = $mapper->getEntityType('Person');
$type->validateOnSave();

9.8.2. Setting up

You can set up validation in the init method of your mapper class.

<?php
class PersonMapper extends Xyster_Orm_Mapper
{
        // protected $_domain, etc.

        public function init()
        {
            $this->getEntityType()
                ->addValidator('name', new Zend_Validate_Alnum);
        }
}

When the name property is set, the validator will ensure that the value passed contains only alphanumeric characters. If validation fails, an exception is thrown.