Grigor
Grigor

Reputation: 4049

CodeIgniter form validation, show errors in order

Lets say I have a login form and it has fields username and password. Both of the fields are required to be filled in and when you submit the form it has two different lines for them.

Username field is required. Password field is required.

What I want to do is to show only the username field errors and when they don't have any errors with username field, it will show the password field errors.

How would this be done?

Also, I remember there is a way to show errors only regarding a field, what was the snippet for it?

Upvotes: 2

Views: 336

Answers (1)

WoMo
WoMo

Reputation: 7256

I suggest using a custom callback function tied to just one input, that checks both inputs and conditionally sets the desired message.

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class YourController extends CI_Controller {

    public function save() 
    {
        //.... Your controller method called on submit

        $this->load->library('form_validation');

        // Build validation rules array
        $validation_rules = array(
                                array(
                                    'field' => 'username',
                                    'label' => 'Username',
                                    'rules' => 'trim|xss_clean|callback_required_inputs'
                                    ),
                                array(
                                    'field' => 'password',
                                    'label' => 'Password',
                                    'rules' => 'trim|xss_clean'
                                    )
                                );
        $this->form_validation->set_rules($validation_rules);
        $valid = $this->form_validation->run();

        // Handle $valid success (true) or failure (false)
        if($valid)
        {
            //
        }
        else
        {
            //
        }
    }


    public function required_inputs()
    {
        if( ! $this->input->post('username'))
        {
            $this->form_validation->set_message('required_inputs', 'The Username field is required');
            return FALSE;
        }
        else if ($this->input->post('username') AND ! $this->input->post('password'))
        {
            $this->form_validation->set_message('required_inputs', 'The Password field is required');
            return FALSE;
        }

        return TRUE;
    }
}

Upvotes: 1

Related Questions