-
Notifications
You must be signed in to change notification settings - Fork 0
Basics of Validation class
Prepare a class to accept validation rules.
- You must use
Larium\Validations\Validate
trait inside your class. - Class mustimplement Larium\Validations\ValidatableInterface`.
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
use Larium\Validations\ValidatableInterface;
use Larium\Validations\Validate;
class Topic implements ValidatableInterface
{
use Validate;
public $approved;
}
There are two ways to define validation rules in a class.
Topic::validatesNumericalityOf('approved'); # This will check if approved property is numeric.
You can define validation rules outside of class definition, in any part of your code.
The Helper pattern of method is validates{Validator}Of where {Validator} is the name of class of available validators.
If you want to apply a custom validator yous should use validatesWith static method
Topic::validatesWith('Acme\MyCustomValidator', 'approved');
Create as protected method called validations.
Inside this method, define validations by calling $this->validates
method.
Parameters you should pass to $this->validates
method are:
- $attribute. A string of class property to validate aor an array of strings.
- $validators. An array that define the validator with options.
The format of $validators parameter is described below.
<?php
array(
'Numericality' => array( # The name of Validator class
'allow_null' => true, # Validator options. Options vary depending of validator.
'only_integer' => true,
'message' => 'Not a number'
)
);
If you want to define a validator without options then yous hould define it like this:
<?php
array(
'Numericality' => true
);
Validator options structure applies to static method Helper too,
A full example of class:
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
use Larium\Validations\ValidatableInterface;
use Larium\Validations\Validate;
class Topic implements ValidatableInterface
{
use Validate;
public $title;
public $content;
public $approved;
protected function validations()
{
$this->validates(
'approved',
array(
'Numericality' => true
)
);
$this->validates(
array('title', 'content'),
array(
'Presence' => array(
'message' => 'Not blank'
)
)
);
}
}
To check if a class is valid according to validation rules you defined, call isValid
method.
<?php
$topic = new Topic();
$topic->isValid() # returns boolean true or false.
$errors = $topic->getErrors() # get an Error object.
Error object extends ArrayIterator class so can be accessed as array and can beiterated too.
You can also get a plain array with error notificaton by calling
$topic->getErrors()->getArrayCopy();