custom validation in codeigniter for username using callback function
custom validation in codeigniter using callback function is easy way to validate input field on form dynamically. We can add custom validation to any input field before insertion in DB. CodeIgniter provide all basic validation with its form_validation class like required, numeric, min_length, max_length, alpha, alpha_numeric etc.
But If we want to add our custom validation for any particular field (mainly for the checking username availability). we can use its callback technique.
//Apply to any input field...
$this->form_validation->set_rules('username', 'Username', 'required|numeric|callback_check_username|trim');
//here callback_check_username is the keyword which call check_username function from same class for validation.
//$username is passed automatically to this function which is the value entered by the User.
//This function checks the availability of the username in Database.
$return_value = $this->user_model->check_username($username);
//set Error message.
$this->form_validation->set_message('username_check', 'Sorry, This username is already used by another user please select another one');
//after satisfying our conditions return TRUE to the origin with no errors.
Here $username is passed automatically to check_username function, we can use our custom rules over here to validate it.
Along with CodeIgniters basic validations you can use your custom conditions (like regular expressions) for a validation on any input field. you can also use regular expression to validate it in your way.