1

I want to create custom validation rule in CodeIgniter 3 but I want to validate posted array (not a string). In CodeIgniter docs, I saw array are also supported.

HTML:

<select name="bonus[]" class="form-control"> ... </select>
<select name="bonus[]" class="form-control"> ... </select>
<select name="bonus[]" class="form-control"> ... </select>

VALIDATION:

$this->form_validation->set_rules("bonus[]", "Bonuses", "all_unique");

VALIDATION RULE all_unique

public function all_unique($array)
{           
    $this->CI->form_validation->set_message('all_unique', '%s are not unique.');

    if(count(array_unique($array))<count($array))
    {
        // Array has duplicates
        return FALSE;
    }
    else
    {
        // Array does not have duplicates
        return TRUE;
    }
}

In general I want to check if selected bonuses are not duplicate. (Number of select bonus fields can vary.)

The problem with this is the value passed to all_unique validation method is passed as a string not as an array, it is the value of the first bonus[] field. How can I validate array of send bonus[].

1 Answer 1

1

You need to use callback in set_message to call all_unique function

$this->form_validation->set_rules("bonus[]", "Bonuses", "callback_all_unique");

To get array field value inside call back use post method as

function all_unique()
{           
    $array = $this->input->post('bonus');// get bonus value
    $this->CI->form_validation->set_message('all_unique', '%s are not unique.');

    if(count(array_unique($array))<count($array))
    {
        // Array has duplicates
        return FALSE;
    }
    else
    {
        // Array does not have duplicates
        return TRUE;
    }
}
Sign up to request clarification or add additional context in comments.

6 Comments

I don't mention this. I override ValidationForm library. It this case I think it isn't a problem.
How you override it??? and validation rule is is_unique not all_unique
I mean i create own MY_Form_validation.php file in application/libraries. And my custom validation rules are there.
okk have you check with $array = $this->input->post('bonus'); inside your function???
Yes this works, but i need something more abstract. In example require funcion in CI library works fine with arrays.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.