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:
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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
Messages
no
iol
Sorry, it has to be "max" with a value of -18 years, of course. And then there'll be the point where you run into unix timestamp boundaries, but in the case of 18 years, that shouldn't be an issue unless you travel back in time ;)
Since 1.0 beta 8, you can use strtotime() syntax in min and max params for the date validator. Making sure the person is at least 18 years old would thus be as simple as setting the value for "min" to "+18 years" in a regular AgaviDateTimeValidator. See the associated ticket #1018 (http://trac.agavi.org/ticket/1018) for details.
lol


