Extends
lithium\core\StaticObject
An important part of describing the business logic of a model class is defining the
validation rules. In Lithium models, rules are defined through the `$validates` class
property, and are used by this method before saving to verify the correctness of the data
being sent to the backend data source.
Note that these are application-level validation rules, and do not
interact with any rules or constraints defined in your data source. If such constraints fail,
an exception will be thrown by the database layer. The `validates()` method only checks
against the rules defined in application code.
This method uses the `Validator` class to perform data validation. An array representation of
the entity object to be tested is passed to the `check()` method, along with the model's
validation rules. Any rules defined in the `Validator` class can be used to validate fields.
See the `Validator` class to add custom rules, or override built-in rules.
Parameters
- string $entity Model entity to validate. Typically either a `Record` or `Document` object. In the following example: {{{ $post = Posts::create($data); $success = $post->validates(); }}} The `$entity` parameter is equal to the `$post` object instance.
- array $options Available options: - `'rules'` _array_: If specified, this array will _replace_ the default validation rules defined in `$validates`. - `'events'` _mixed_: A string or array defining one or more validation _events_. Events are different contexts in which data events can occur, and correspond to the optional `'on'` key in validation rules. For example, by default, `'events'` is set to either `'create'` or `'update'`, depending on whether `$entity` already exists. Then, individual rules can specify `'on' => 'create'` or `'on' => 'update'` to only be applied at certain times. Using this parameter, you can set up custom events in your rules as well, such as `'on' => 'login'`. Note that when defining validation rules, the `'on'` key can also be an array of multiple events.
Returns
boolean Returns `true` if all validation rules on all fields succeed, otherwise `false`. After validation, the messages for any validation failures are assigned to the entity, and accessible through the `errors()` method of the entity object.Source
public function validates($entity, array $options = array()) {
$defaults = array(
'rules' => $this->validates,
'events' => $entity->exists() ? 'update' : 'create',
'model' => get_called_class()
);
$options += $defaults;
$self = static::_object();
$validator = static::$_classes['validator'];
$params = compact('entity', 'options');
$filter = function($parent, $params) use (&$self, $validator) {
$entity = $params['entity'];
$options = $params['options'];
$rules = $options['rules'];
unset($options['rules']);
if ($errors = $validator::check($entity->data(), $rules, $options)) {
$entity->errors($errors);
}
return empty($errors);
};
return static::_filter(__FUNCTION__, $params, $filter);
}