![]() |
|
Snippets |
|
test 2
Say you wanted to validate that someone was over 18 years of age, its acutally quite simple once you know what your doing, but it took me a while to work out all the bits, so i thought i would put it in here to save some one a bit of time...
on the template you have
<p> <label for="date_of_birth">Date of Birth:</label> <?php echo form_error('day'); ?> <?php echo form_error('month'); ?> <?php echo form_error('year'); ?> <?php echo select_day_tag('day', $sf_params->get('day')) ?> <?php echo select_month_tag('month', $sf_params->get('month')) ?> <?php echo select_year_tag('year', $sf_params->get('year'),array('year_start'=>'1900','year_end'=>date("Y"))) ?> </p>
in signup.yml (due to the way i built my form, you dont actually need to validate the day and month, since there is no way to leave them empty, but i have put the code in for completness)
methods:
post: [day, month, year, gender]
names:
day:
required: true
required_msg: You must verify your age.
month:
required: true
required_msg: You must verify your age.
year:
required: true
required_msg: You must verify your age.
validators: ageValidator
ageValidator:
class: myAgeValidator
param:
too_young_error: You must be over 18 to enter.
now in /lib/AgeValidator.class.php, we put the code to check the dates.
class myAgeValidator extends sfValidator { public function initialize($context, $parameters = null) { // initialize parent parent::initialize($context); // set defaults $this->setParameter('too_young_error', 'Invalid input'); $this->getParameterHolder()->add($parameters); return true; } public function execute(&$value, &$error) { // get the passed values for the date fields $day_param = sfContext::getInstance()->getRequest()->getParameter('day'); $month_param = sfContext::getInstance()->getRequest()->getParameter('month'); $year_param = sfContext::getInstance()->getRequest()->getParameter('year'); $min_age=strtotime("-18 YEAR"); $entrant_age= strtotime( $year_param . "-" . $month_param . "-" . $day_param); # just in case ;-) #sfContext::getInstance()->getLogger()->debug('min_age->'.$min_age); #sfContext::getInstance()->getLogger()->debug('entrant_age->'.$entrant_age); #sfContext::getInstance()->getLogger()->debug('param-day->'.$day_param); #sfContext::getInstance()->getLogger()->debug('param-month->'.$month_param); #sfContext::getInstance()->getLogger()->debug('param-year->'.$year_param); if ($entrant_age <$min_age ){ return true; } $error = this->getParameter('too_young_error'); return false; } }