Alex Rivera | Logout

validation max_length, min_length in codeigniter

Asked 2011-12-13T09:44:30.640
9

I am getting an error when trying to set custom validation messages in CodeIgniter for the min_length and max_length validation constraints.

These are my validation rules:

$this->form_validation->set_rules('username', 'Username', 'required|xss_clean|min_length[6]|max_length[10]');
$this->form_validation->set_rules('password', 'Password', 'required|min_length[8]|max_length[20]';

These are my custom validation message:

$this->form_validation->set_message('min_length[3]', '%s: the minimum of characters is three');
$this->form_validation->set_message('max_length[20]', '%s:the maximum of characters is 20');

In my example we have two fields, but I have many fields with different minimum and maximum length values. They all have a specific constraint validations. This messages doesn't work. The message appears by default. Thanks for your help.

Edit
Report

1 Answer

10
$this->form_validation->set_rules('password', 'Password', 'required|min_length[8]|max_length[20]';

is missing a closing bracket -- ):

$this->form_validation->set_rules('password', 'Password', 'required|min_length[8]|max_length[20]');


Update
Perhaps using a callback function would be better? E.g.:

$this->form_validation->set_rules('username', 'Username', 'required|xss_clean|callback__check_length[6,10]');


/**
 * Callback function. Checks if the length of the user's input
 * conforms to minimum and maximum character length requirements
 *
 * @param  string
 * @param  int
 * @param  int
 * @return bool
 */
function _check_length($input, $min, $max)
{
    $length = strlen($input);

    if ($length <= $max && $length >= $min)
    {
        return TRUE;
    }
    elseif ($length < $min)
    {
        $this->form_validation->set_message('_check_length', 'Minimum number of characters is ' . $min);
        return FALSE;        
    }
    elseif ($length > $max)
    {
        $this->form_validation->set_message('_check_length', 'Maximum number of characters is ' . $max);
        return FALSE;        
    }
}
answered 2011-12-13T11:17:23.593

Your Answer