Code snippets for symfony 1.x


Refine Tags

Snippets tagged "dateofbirth"

Age Validation

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

  <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"))) ?>

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)

  post: [day, month, year, gender]
    required:     true
    required_msg: You must verify your age.
    required:     true
    required_msg: You must verify your age.
    required:     true
    required_msg: You must verify your age.
    validators:   ageValidator
    class:         myAgeValidator
      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
    // set defaults
    $this->setParameter('too_young_error', 'Invalid input');
    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 ;-)
if ($entrant_age <$min_age ){
    return true;
$error = this->getParameter('too_young_error');
return false;
by excessive demon on 2008-04-16, tagged age  dateofbirth  validation