Welcome Guest, Not a member yet? Register   Sign In
Form_validation: cann't select- and checkboxes be required?
#1

[eluser]Chicken's Egg[/eluser]
I have created a form with a select box in my view. In my controller is a rule for this select box: it is required. However, if non of the options in the select box are selected the form validates TRUE.
I noticed the same problem with check-boxes. If you choose 'required' as rule for a check box and the checkbox is not checked, the form wil validate true anyway. The user guide doesn't mention this. Or did I miss the point?

The select box I used for testing looked like:

<select name="aTab_Id" id="Tab" size="4">
<option value="2">Option B</option>
<option value="3">Option C</option>
<option value="1">Option A</option>
</select>

And the accompanying rule in my controller looked like:
array(
'field' => 'aTab_Id',
'label' => 'lang:post_aTab_Id',
'rules' => 'required'
),

[edit]
Mistake found: De CI Library Form_validation does allow and utilize the rule 'required' for check boxes and select boxes too. However, the extension of the Form_validation - which I use to validate file uploads too - caused the problem here. Happily that bug is solved, cause it is really a great extention which you can find here.
#2

[eluser]skunkbad[/eluser]
I do something like this for check boxes on my estimates page, Brian's Web Design - Website Estimates Page :

Code:
$yesArray = array(
    'products_pages'        =>        'PRODUCTS PAGE',
    'links_page'            =>        'LINKS PAGE',
    'FAQs_page'                =>        'FAQS PAGE'
);
foreach($yesArray as $field => $label){
    $config[] = array('field' => $field, 'label' => $label, 'rules' => 'callback__checkYes');
}
$this->form_validation->set_rules($config);

and then there is the _checkYes callback:

Code:
public function _checkYes($yes){
    if($yes != 'yes' && isset($yes)){
        $this->form_validation->set_message('_checkYes', 'The <span class="redfield">%s</span> field contains invalid data');
        return FALSE;
    }else{
        return $yes;
    }
}

You can check my page and view the source code for the HTML if you like.

Then I have this for a select box:

Code:
$this->form_validation->set_rules('approx_pages', 'ESTIMATED WEBSITE SIZE' , 'trim|xss_clean|callback__notNull');

The _notNull callback looks like this:

Code:
public function _notNull($string) {
    if($string == '' || $string == NULL){
        $this->form_validation->set_message('_notNull', 'A <span class="redfield">%s</span> selection is required');
        return FALSE;
    }else{
        if($this->_cleanField($string) != FALSE){
            return $string;
        }
    }
}

Not sure if this is the "right" way to do it, but it works.




Theme © iAndrew 2016 - Forum software by © MyBB