dracoblue.net

Agavi Age Validator

Hello,

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');
            $this->removeParameter('min');
            $this->setParameter('max',$min_date->format('Y-m-d'));
        }
        if (null !== $max) {
            $max_date = new DateTime(($max*(-1)).' years');
            if (null !== $min) $this->removeParameter('max'); // remove only, if _min_ was not set
            $this->setParameter('min',$max_date->format('Y-m-d'));
        }
        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

Give something back

Were my blog posts useful to you? If you want to give back, support one of these charities, too!

Report hate in social media Campact e.V. With our technology and your help, we protect the oceans from plastic waste. Gesellschaft fur Freiheitsrechte e. V. The civil eye in the mediterranean

Recent Dev-Articles

Read recently

Recent Files

About