Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I validate a form field in Codeigniter when using Get parameters?

I have a form that worked perfectly until I switched the form to method="get". Now I can't get form_validation->run() to evaluate to TRUE.

This is how I open the form:

echo form_open( '', array( 'method' => 'get' ) );

This is the only piece that needs to validate:

$this->form_validation->set_rules( 'states', 'states', 'required' );

This is how I check to see if the form is validated:

if( $this->form_validation->run() == FALSE )

Is there something else I need to do to use Get parameters? I have get parameters turned on in the config ( $config['allow_get_array'] = TRUE; ). The form works ok if I skip the validation, so I know the CI system is reading the url fine.

like image 282
T. Brian Jones Avatar asked May 09 '12 22:05

T. Brian Jones


People also ask

How to give form validation in CodeIgniter?

CodeIgniter lets you set as many validation rules as you need for a given field, cascading them in order, and it even lets you prep and pre-process the field data at the same time. To set validation rules you will use the set_rules() method: $this->form_validation->set_rules();

How do you validate a form?

Basic Validation − First of all, the form must be checked to make sure all the mandatory fields are filled in. It would require just a loop through each field in the form and check for data. Data Format Validation − Secondly, the data that is entered must be checked for correct form and value.

How to change form validation Error message in CodeIgniter?

PHP_EOL; $data['err'] = $err; $this->load->view('viewname', $data); } else if ($this->form_validation->run() == true ) { #code... } else.. after setting your custom message to $err variable, print it on your view. Save this answer.


2 Answers

For CodeIgniter 3, you can pass the GET array into the set_data function. For example:
$this->form_validation->set_data($this->input->get());

like image 84
gX. Avatar answered Sep 20 '22 00:09

gX.


Codeigniter has changed since some of these posts. I think gX's answer is correct.

The instructions in the user manual, specifically section Validating an Array (other than $POST), worked great for me (as of today) and it's very simple.

Before your $this->form_validation->set_rules line, you specify the array to be validated:

$data = array(
    'username' => 'johndoe',
    'password' => 'mypassword',
    'passconf' => 'mypassword');

$this->form_validation->set_data($data);
like image 45
Cyclist Avatar answered Sep 20 '22 00:09

Cyclist