form_validation Codeigniter using GET

Asked

Viewed 328 times

2

is it possible to validate a form input using the GET method? When I define that the form method is POST the form_validation works but when I define that is 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 didn’t think it was quite right:

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

1 answer

4


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

Before executing any set_rule you must use the $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')
));

Then 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';
    }
}
  • 1

    It worked perfectly. Thanks!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.