Agavi Age Validator


a friend and I were wondering how would be best practice to implement an age validator in agavi. Since agavi already has the AgaviDateTimeValidator, my initial idea was, to extend that one and just re-interpret the min/max-parameters.

But a

minimum age of 18 would result into a max date of 1991-02-08. And a maximum age of 20 would result into a min date of 1989-02-08. So I had to swap the throwError's for max and min.

The resulting code:

class AgeValidator extends AgaviDateTimeValidator {
    protected function validate() {
        $min = $this->getParameter('min',null);
        $max = $this->getParameter('max',null);
        if (null !== $min) {
            $min_date = new DateTime(($min*(-1)).' years');
        if (null !== $max) {
            $max_date = new DateTime(($max*(-1)).' years');
            if (null !== $min) $this->removeParameter('max'); // remove only, if _min_ was not set
        return parent::validate();
    protected function throwError($index = null, $affectedArgument = null, $argumentsRelative = false, $setAffected = false)
        if ($index == 'max' || $index == 'min') {
            // Swap those, since we faked them for the default behaviour
            $index = ($index == 'max' ? 'min' : 'max');
        return parent::throwError($index, $affectedArgument, $argumentsRelative, $setAffected);

Do you got any other ideas how to solve that in a gentle way?

  • Draco
In agavi, open source, php, validator by
@ 08 Feb 2009, Comments at Reddit & Hackernews