Arunoda Samarasinghe
Arunoda Samarasinghe

Reputation: 49

Multi Select Drop Down validation in Codeigniter

I'm trying to validate multi-select dropdown form validation in Codeigniter and I'm using custom validate callback method for the validation. I tried several StackOverflow answers, but none of them worked for me. Am I missing something?

This is my view code.

<?php echo form_open_multipart('Register/user_register') ?>
    	<div class="form-group">
				<label for="musicGen">Select Your Music Genre</label>
				<?php echo form_error('musicGen'); ?>
				<select class="form-control" name="musicGen[]" multiple="multiple" id="musicGen">
					<?php
					foreach ($genre as $row) {
						echo '<option class="form-control" value="' . $row->genreId . '">' . $row->genreName . '</option>';
					}
					?>
				</select>
			</div>
<?php echo form_close() ?>

This is my controller.

$this->form_validation->set_rules('musicGen', 'Music Genre', 'required|callback_multiple_select');

public function multiple_select()
	{
		$music_genre = $this->input->post('musicGen');

		if (is_null($music_genre)) {
			$this->form_validation->set_message('multiple_select', 'Select at least one Music Genre');
			return false;
		} else {
			return true;
		}

	}

Upvotes: 0

Views: 1181

Answers (2)

Bhavesh Parab
Bhavesh Parab

Reputation: 83

No need to use a callback function, unless you want a user to select more than one option. You can use the below code in your code

if (empty($_POST['musicGen'])) {
      $this->form_validation->set_rules('musicGen', 'Music Genre', 'required',array('required' =>'Select at least one Music Genre'));
   }

Upvotes: 2

Vickel
Vickel

Reputation: 7997

You have 2 possibilities to approach this:

use just validation rule "required", for that you may not index the name of the input field, change it to name="musicGen"`:

<select class="form-control" name="musicGen" multiple="multiple" id="musicGen">

and

$this->form_validation->set_rules('musicGen', 'Music Genre', 'required'); 

or you use the callback function "multiple_select" with the indexed name field. This makes more sense, as your callback requires to have at least one option selected (checking with is_null) You could also want to check for more than one option selected, do this with count

<select class="form-control" name="musicGen[]" multiple="multiple" id="musicGen">

and simple change you validation rule to:

$this->form_validation->set_rules('musicGen', 'Music Genre', 'callback_multiple_select');

public function multiple_select()
{
    $music_genre = $this->input->post('musicGen');
    if (count($music_genre)<2) {
        $this->form_validation->set_message('multiple_select', 'Select at least two Music Genre');
        return false;
    } else {
        return true;
    }
}

Upvotes: 1

Related Questions