form_validation Codeigniter using GET

2

Is it possible to validate an input of a form using the GET method? When I define the form's method is POST the form_validation works but when I define it's GET the validation returns me false. The code is basically this:

HTML

<form method="GET" action="<?=base_url('pesquisar');?>" role="form">
    <div class="input-group">
        <input type="text" class="form-control" name="busca" required>
            <span class="input-group-btn">
                <button type="submit" class="btn btn-plan">Pesquisar</button>
            </span>
     </div><!-- /input-group -->
</form>

CONTROLLER

public function pesquisar() {
    $this->form_validation->set_rules('busca', 'Termo de Busca', 'required|trim');

    if ($this->form_validation->run()) {
        echo $this->input->get('busca');
    } else {
         echo 'não validou'; // Sempre entra aqui
    }
}

I saw the following solution, but I did not think it was right:

$_POST['busca'] = $this->input->get('busca'); // só então executar a validação...

    
asked by anonymous 19.05.2016 / 00:12

1 answer

4

According to the codeigniter3 documentation you can validate other arrays out $_POST

Before running any set_rule you should use $this->form_validation->set_data adding the values you want.

It would look something like:

$this->form_validation->set_data($_GET);

Or "better":

$this->form_validation->set_data(array(
    'busca' => $this->input->get('busca')
));

Next would come the set_rule , getting something like:

public function pesquisar()
{
    $busca = $this->input->get('busca');

    $this->form_validation->set_data(array( 'busca' => $busca ));
    $this->form_validation->set_rules('busca', 'Termo de Busca', 'required|trim');

    if ($this->form_validation->run()) {
        echo $busca;
    } else {
         echo 'não validou';
    }
}
    
19.05.2016 / 02:02