Wednesday, February 17, 2016

[Codeigniter 2][Resolved] Unable to access an error message corresponding to your field name

This is the example code return the validation error  message as "Unable to access an error message corresponding to your field name":
function _article_valid() {
    $this->load->helper(array('form', 'url'));
    $this->load->library('form_validation');
    $this->form_validation->set_rules('title', 'Title', 'required');
    $this->form_validation->set_rules('url', 'Url', 'callback_url_check');
    return $this->form_validation->run();
}    

function url_check($url){
    if ($url == 'test') {
        $this->form_validation->set_message('url', 'The field can not be the word "test"');
        return FALSE;
    }else{
        return TRUE;
    }  
}
And i found the problem is caused by the text in red with yellow background shown above.

Firstly, according example code shown at official site, that value same as the callback function name, and also same as function name after "callback_" rule prefix :




and then I change the first argument of set_message which's same as the callback function name and found its work.

function url_check($url){
    if ($url == 'test') {
        $this->form_validation->set_message('url_check', 'The field can not be the word "test"');
        return FALSE;
    }else{
        return TRUE;
    }  
}

of cos it's work for this too:
function _article_valid() {
    $this->load->helper(array('form', 'url'));
    $this->load->library('form_validation');
    $this->form_validation->set_rules('title', 'Title', 'required');
    $this->form_validation->set_rules('pwd', 'pwd', 'callback_pwd_valid');
    return $this->form_validation->run();
}    

function pwd_valid($pwd){
    if ($pwd == 'test') {
        $this->form_validation->set_message('pwd_valid', 'The field can not be the word "test"');
        return FALSE;
    }else{
        return TRUE;
    }  
}
And according the article by brianantonelli in brianistech.wordpress.com, you can also change the first argument of set_message function to __FUNCTION__ , also is a solution. (tested works in this articcase)
function url_check($url){
    if ($url == 'test') {
        $this->form_validation->set_message(__FUNCTION__, 'The field can not be the word "test"');
        return FALSE;
    }else{
        return TRUE;
    }  

Reference:

http://www.codeigniter.com/userguide2/libraries/form_validation.html#callbacks 
https://brianistech.wordpress.com/2010/11/22/unable-to-access-an-error-message-corresponding-to-your-field-name/

1 comment :