这是我用来验证生日(并重新填充下拉菜单)的精简版本。仅供参考,我在这里有一些逻辑,您可能想要删除。
验证规则:
$this->form_validation->set_rule('birthdate-month','Birthdate Month','required|is_natural_no_zero|greater_than[0]|less_than[13]');
$this->form_validation->set_rule('birthdate-day','Birthdate Day','required|is_natural_no_zero|greater_than[0]|less_than[32]');
$this->form_validation->set_rule('birthdate-year','Birthdate Year','required|is_natural_no_zero|greater_than[1930]|less_than['.(date("Y") - 18).']');
控制器:
if ($this->form_validation->run()) {
$birthdate = array(
$this->form_validation->set_value('birthdate-year'),
$this->form_validation->set_value('birthdate-month'),
$this->form_validation->set_value('birthdate-day')
);
$data = array(
'birthdate' => implode("-", $birthdate)
);
}
// Then pass $data to your model and do whatever you want, i.e.:
$this->user_model->update_user($data);
然后是视图中的 PHP/HTML:
<select name="birthdate-month" id="birthdate-month">
<option value=""></option>
<?php foreach($months as $month_number => $month_name) { ?>
<option value="<?php echo $month_number; ?>" <?php echo set_select('birthdate-month', $month_number); ?>><?php echo $month_name; ?></option>
<?php } ?>
</select>
<select name="birthdate-day" id="birthdate-day">
<option value=""></option>
<?php for($i=1; $i<=31; $i++) { ?>
<option value="<?php echo $i; ?>" <?php echo set_select('birthdate-day', $i); ?>><?php echo $i; ?></option>
<?php } ?>
</select>
<select name="birthdate-year" id="birthdate-year">
<option value=""></option>
<?php for($i=(date("Y") - 18); $i>=1930; $i--) { ?>
<option value="<?php echo $i; ?>" <?php echo set_select('birthdate-year', $i); ?>><?php echo $i; ?></option>
<?php } ?>
</select>
仅供参考,$months
是一个数组:
array(
'01' => 'January',
'02' => 'February',
'03' => 'March',
'04' => 'April',
'05' => 'May',
'06' => 'June',
'07' => 'July',
'08' => 'August',
'09' => 'September',
'10' => 'October',
'11' => 'November',
'12' => 'December'
);