CodeIgniter Forums
Validation: one of two field required - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: CodeIgniter 4 (https://forum.codeigniter.com/forum-28.html)
+--- Forum: CodeIgniter 4 Support (https://forum.codeigniter.com/forum-30.html)
+--- Thread: Validation: one of two field required (/thread-78426.html)



Validation: one of two field required - Codinglander - 01-18-2021

Hello.

I have a form in which two fields are related.
I want at least one of the two fields to be filled out. It is also conceivable that both are filled in, but not that neither is filled out.
Is there a validation rule for this? Or can someone help me with a solution?

Greetings,

Kigh ...


RE: Validation: one of two field required - kleber - 01-18-2021

https://codeigniter.com/userguide3/libraries/form_validation.html#callbacks-your-own-validation-methods

I think you can create your own validation rule for this case. Or you can follow the code below. I think you can do that on CI4 too.


PHP Code:
if(!isset($_POST['field_one']) and !isset($_POST['field_two'])){

$this->form_validation->set_message('required''At least one field must be filled!');

$this->form_validation->set_rules('field_one''field one''required');
$this->form_validation->set_rules('field_two''field two''required');





RE: Validation: one of two field required - Codinglander - 01-18-2021

Hmmm... okay, today afternoon I#ll try it...


RE: Validation: one of two field required - AndresHDZ - 01-19-2021

For CI 4:

PHP Code:
        if($this->request->getPost('field_one') == '' && $this->request->getPost('field_two')){
            $error_msg 'You need to fill field_one or field_two.';
        }else{
            $validation Services::validation();
            if($this->request->getPost('field_one')){
                $validation->setRule('field_one''label 1''YOUR RULES HERE');
            }
            if($this->request->getPost('field_two')){
                $validation->setRule('field_two''label 2''YOUR RULES HERE');
            }
            if($validation->withRequest($this->request)->run() == false){
                $error_msg $validation->listErrors();
            }else{
                /* Here your success code */
            }
        


Where $error_msg contains your error.