Search code examples
phpcodeigniter

CodeIgniter getting form field value to lowercase


I have just started on learning how to use CodeIgniter and have never use any framework before so I only know a bit of how is the flow. Right now I have 1 issue that I want to set the input username to lowercase and I do not have any idea how to write the function for the convert_lowercase().

Below is my code:

public function signup_validation()
    {
        $this ->load->library('form_validation');

        $this->form_validation->set_rules('username', 'Username', 'required|trim|is_unique[userinfo.username]|convert_lowercase');
        $this->form_validation->set_rules('password', 'Password', 'required|trim');
        $this->form_validation->set_rules('cpassword', 'Confirm Password', 'required|trim|matches[password]');

        $this->form_validation->set_message('is_unique', 'That Username Already Exists.');

        if($this->form_validation->run()){
        }else{
            $this->load->view('signup');
        }
    }

public function convert_lowercase()
    {
        strtolower($this->input->post('username'));
    }

I am not sure am I doing the right way.

And is it best to just put the strtolower in the set_rules parameter? Or it is best to put in a function?

And if separate it, how should it be done and how do I get the final username data to insert into database?

Any kind souls out there can help me on this?

Thanks in advance.


Solution

  • You can provide php native functions for form validation to CodeIgniter. Here is how your code should be

    public function signup_validation()
    {
        $this ->load->library('form_validation');
    
        $this->form_validation->set_rules('username', 'Username', 'required|trim|is_unique[userinfo.username]|strtolower');
        $this->form_validation->set_rules('password', 'Password', 'required|trim');
        $this->form_validation->set_rules('cpassword', 'Confirm Password', 'required|trim|matches[password]');
    
        $this->form_validation->set_message('is_unique', 'That Username Already Exists.');
    
        if($this->form_validation->run()){
        }else{
            $this->load->view('signup');
        }
    }
    

    You should check their documentation on form validation: http://ellislab.com/codeigniter%20/user-guide/libraries/form_validation.html