Symfony base global validator: sfGlobalValidator
Symfony | Technical | November 25, 2010
Usually, when creating a new general validator for a symfony 1 form there are some steps you must follow. These steps are repeated everytime a new general validator is created. Steps like:
/** * Constructor. * * @param array An array of options * @param array An array of error messages * * @see sfValidatorSchema */ public function __construct($options = array(), $messages = array()) { parent::__construct(null, $options, $messages); }
In this case, this is because a general validator extends from sfValidatorSchema class and its constructor expects as first parameter a set of fields. This code block must be repeated on every general validator you create.
A general validator usually must be called once all the mandatory fields of the form are not empty. Else, in the errors will be shown the general validator error, too. Even though it did not have the data to correctly validate the input.
With this in mind a method like the next one could save our day:
/** * Returns true if any value is blank. * * @param array $values The values to evaluate * * @return boolean True if any value is blank, otherwise false */ public function hasEmptyValues($values) { foreach ($values as $value) { if (empty($value)) { return true; } } }
It can be used like:
protected function doClean($values) { if ($this->hasEmptyValues($values)) { return $values; } ... }
This way every time there is an empty field the general validator will not show any error.
Now this two simple ideas can be melt into a handy parent class for all your general symfony validators: sfGlobalValidator
/** * sfGlobalValidator * * This validator is the parent of any global validator * as pre and post validators. * * @package symfext * @subpackage validator * @author Jonathan Olger Nieto Lajo - johan.nieto.lajo@gmail.com */ class sfGlobalValidator extends sfValidatorSchema { /** * Constructor. * * @param array $options An array of options * @param array $messages An array of error messages * * @see sfValidatorSchema */ public function __construct($options = array(), $messages = array()) { parent::__construct(null, $options, $messages); } /** * Cleans the input value. * * @throws InvalidArgumentException If the values parameter is not an array * * @see sfValidatorSchema */ public function clean($values) { if (!is_array($values)) { throw new InvalidArgumentException('You must pass an array parameter to the clean() method.'); } return parent::clean($values); } /** * Returns true if any value is blank. * * @param array $values The values to evaluate * * @return boolean True if any value is blank, otherwise false */ public function hasEmptyValues($values) { foreach ($values as $value) { if (empty($value)) { return true; } } } }
Now, anytime you need a general validator class, to avoid repeat the same code, make it extend from sfGlobalValidator.