简体   繁体   中英

Form Validation required either two fields or a third one

I've searched for a while around the internet and here on StackOverflow. I've found similar needs, but I'm having a hard time adapting those solutions to my specific need.

I'm using CodeIgniter 2, and I've created a form. I'm using form_validation to validate each values entered in the fields.

Now, I have 2 fields which are used for a period of time, and a third field used for a fileID.

The user must either fill [the period of time] fields, or the [fileID] field, or both.

    $this->form_validation->set_rules('idx_start', 'lang:idx_start', 'trim');           
    $this->form_validation->set_rules('idx_end', 'lang:idx_end', 'trim');       
    $this->form_validation->set_rules('fileID', 'lang:fileID', 'trim');

I tried to look into Callbacks and create a custom validation rule but I can't seem to figure out an easy and efficient way for my need.

Thanks in advance for your help.

You could always create different rules arrays. I do this in a couple of projects.

So something like this in your controller:

if($condition1){
    $rules = $this->my_model->rules1;
} else {
    $rules = $this->my_model->rules2;
}
$this->form_validation->set_rules($rules);

And where $rules1 and $rules2 in 'my_model' would look something like this:

public $rules1 = array(
    'idx_start' => array(
        'field' => 'idx_start',
        'label' => 'start',
        'rules' => 'trim|required'
    ),
    'idx_end' => array(
        'field' => 'idx_end',
        'label' => 'end',
        'rules' => 'trim|required'
    ),
    'fileID' => array(
        'field' => 'fileID',
        'label' => 'file id',
        'rules' => 'trim'
    )
);

public $rules2 = array(
    'idx_start' => array(
        'field' => 'idx_start',
        'label' => 'start',
        'rules' => 'trim'
    ),
    'idx_end' => array(
        'field' => 'idx_end',
        'label' => 'end',
        'rules' => 'trim'
    ),
    'fileID' => array(
        'field' => 'fileID',
        'label' => 'file id',
        'rules' => 'trim|required'
    )
);

Or however they need to be. Hope this helps!

Probably there is better way, but this could work imho:

$this->form_validation->set_rules('fileID', 'lang:fileID', 'trim')
if ( $this->form_validation->run() != true  ) {
    $this->form_validation->set_rules('idx_start', 'lang:idx_start', 'trim');           
    $this->form_validation->set_rules('idx_end', 'lang:idx_end', 'trim');
}
if ( $this->form_validation->run() == false  ) {
    // form failed
} else {
    // form passed
}

I've used following Add in to CodeIgniter for my specific need. http://forum.codeigniter.com/thread-22443.html

Works fine for me. Thanks

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM