kelvin dev kelvin dev - 1 month ago 20
PHP Question

Codeigniter callbacks affecting required validation

I am using codeigniter 3.1.1. I am new to codeigniter and i have ran into a problem i can get figured out. My callback functions seem to affect the required validation in that the required rule seems to be skipped and the callback function gets executed even when the field is empty. Here's my code

$validate_data = array(

array(

'field' => 'pages',
'label' => 'No of pages',
'rules' => 'trim|required|integer|callback_regex_pages'
)
);

$this->form_validation->set_rules($validate_data);
$this->form_validation->set_error_delimiters('<p class="text-danger">','</p>');


My callback function

public function regex_pages(){

if(!preg_match('/^\d(\d)?(\d)?$/',$this->input->post('pages'))){

$this->form_validation->set_message('regex_pages', 'The {field} is not valid!');

return false;

}else{

return true;

}
}//end method regex_pages


This is just one of my many callbacks that behave this way. If I remove the callback rule, the required rule gets executed

This is my output below

My output

Answer

I suggest you to extend your form validation library by making a new library called "MY_form_validation" which will extend "CI_form_validation" and save it in "libraries" folder; After this, put your all callback functions in MY_form_validation and in this way, you will have global available your callbacks, but keep in mind, you no need to set rule with prefix "callback". Here is an example:

$validate_data = array(

    array(

        'field' => 'pages',
        'label' => 'No of pages',
        'rules' => 'trim|required|integer|regex_pages'
        )

);

$this->form_validation->set_rules($validate_data);
$this->form_validation->set_error_delimiters('<p class="text-danger">','</p>');

So in MY_form_validation you will make the function

public function regex_pages($value_to_be_validated){

if(!preg_match('/^\d(\d)?(\d)?$/',$value_to_be_validated)){

$this->set_message('regex_pages', 'The {field} is not valid!');

return false;

}else{

return true;

}