Codeigniter - checkbox form validation
I have a form validation rule in place for a form that has a number of checkboxes:
$this->form_validation->set_rules('groupcheck[]', 'groupcheck', 'required');
If none of my checkboxes are checked upon submission, my code never gets past the validation->run as the variable does not exist:
if ($this->form_validation->run()):
If i surround my validation rule with a check for the var, the validation never passes as there are no other form validation rules:
if(isset($_POST['groupcheck'])):
$this->form_validation->set_rules('groupcheck[]', '开发者_JAVA技巧groupcheck', 'required');
endif;
How can I manage a checkbox validation rule where the var may not exist, and it will be the only form variable?
Regards, Ben.
Don't use isset() in CodeIgniter as CodeIgniter provide better class to check if the POST Variable you are checking is exist or not for example try to use this code instead of your code:
if($this->input->post('groupcheck')):
$this->form_validation->set_rules('groupcheck[]', 'groupcheck', 'required');
endif;
For Guidline using on how to use POST and GET variables in CodeIgniter check the User Guide here: http://codeigniter.com/user_guide/libraries/input.html
I had the same issue. If your checkbox is unchecked then it will never get posted. Remove the set_rules for your checkboxes and after your other form validation rules, try something like:
if ($this->form_validation->run() == TRUE){ // form validation passes
$my_checkbox_ticked = ($this->input->post('my_checkbox')) ? yes : no;
You may compare validation_errors()
after $this->form_validation->run()
if is FALSE
then nothing was validate, so you can do something or show a warning
if ($this->form_validation->run() == FALSE) {
if (validation_errors()) {
echo validation_errors();
} else {
echo 'empty';
}
}
You also need to set button submit
$this->form_validation->set_rules('terminos_form', 'TERM', 'required');
$this->form_validation->set_rules('terminosbox', 'TERM BOX', 'callback__acept_term');
Callback
function _acept_term($str){
if ($str === '1'){
return TRUE;
}
$this->form_validation->set_message('_acept_term', 'Agree to the terms');
return FALSE;
}
HTML
<input type="checkbox" name="terminosbox" value="1"/>
<button type="submit" name="terminos_form" value="1">NEXT</buttom>
精彩评论