woutr_be
woutr_be

Reputation: 9722

CodeIgniter form validation optional based on value

I'm setting up a form with CI and I'm using the form validation to help me with this.

At the moment I have different rules setup, like

$this->form_validation->set_rules('first_name', 'First Name', 'required|xss_clean');

But in my form I have a checkbox, enabling the checkbox will show some new inputs that are required when the checkbox is checked. When the checkbox is unchecked these fields are not required.

What would be the best method to do this in CI?

// Set validation rules
$this->form_validation->set_rules('first_name', 'First Name', 'required|xss_clean');
$this->form_validation->set_rules('last_name', 'Last Name', 'required|xss_clean');
// Some more rules here

if($this->form_validation->run() == true) {
    // Form was validated
}

Upvotes: 0

Views: 6639

Answers (3)

envysea
envysea

Reputation: 1031

I faced something just like this a couple months ago. I just added a short if-statement.

It looked something like this (using address for example):

$this->form_validation->set_rules('home_address', '"Home Address"', 'required|trim|xss_clean|strip_tags');
$this->form_validation->set_rules('unit', '"Unit"', 'trim|xss_clean|strip_tags');
$this->form_validation->set_rules('city', '"City"', 'required|trim|xss_clean|strip_tags');
$this->form_validation->set_rules('state', '"State"', 'required|trim|xss_clean|strip_tags');
$this->form_validation->set_rules('zip', '"Zip"', 'required|trim|xss_clean|strip_tags');

//checkbox formatted like this in the view: form_checkbox('has_second_address', 'accept'); 
if ($this->input->post('has_second_address') == 'accept')
{
    $this->form_validation->set_rules('street_address_2', '"Street Address 2"', 'required|trim|xss_clean|strip_tags');
    $this->form_validation->set_rules('state_2', '"State 2"', 'required|trim|xss_clean|strip_tags');
    $this->form_validation->set_rules('city_2', '"City 2"', 'required|trim|xss_clean|strip_tags');
    $this->form_validation->set_rules('zip_2', '"Zip 2"', 'required|trim|xss_clean|strip_tags');
}

if($this->form_validation->run() == true) {
    //example
    //will return FALSE if empty
    $street_address_2 = $this->input->post('street_address_2');
    //and so on...
}

I'm not sure if this is the Codeigniter way or not, but last time I checked I couldn't find a "best method" way. This definitely gets the job done, and it at minimum allows you to take control over a users $_POST variables.

Anyways, I hope this helps

Upvotes: 7

Mudshark
Mudshark

Reputation: 3253

if($this->input->post('checkbox_name')){
    // add more validation rules here
}

Upvotes: 6

user1157393
user1157393

Reputation:

you could use javascript / jquery to set the value of a hidden field to true or false depending of whether the checkbox has been checked.

Then in your controller check with a conditional

if ($hidden_field) {
   //run more validation.
}

Upvotes: 0

Related Questions