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.
Example :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
//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.
function check_username($username)
{
//$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);
if ($return_value)
{
//set Error message.
$this->form_validation->set_message('username_check', 'Sorry, This username is already used by another user please select another one');
return FALSE;
}
else
{
//after satisfying our conditions return TRUE to the origin with no errors.
return TRUE;
}
}
|
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