0
votes

In Codeigniter 2 is there a way to custom validation message in the below array and not as $this->form_validation->set_message

     $ValidationRules = array(
               array('field'   => 'address_line1', 
                     'label'   => 'Address Line1', 
                     'rules'   => 'trim|min_length[2]|max_length[40]|xss_clean'),
               array('field'   => 'address_line2', 
                     'label'   => 'Address Line2', 
                     'rules'   => 'trim|min_length[2]|max_length[40]|xss_clean'),
               array('field'   => 'address_line3', 
                     'label'   => 'City', 
                     'rules'   => 'trim|min_length[2]|max_length[40]|xss_clean')
                );

    $this->form_validation->set_rules($ValidationRules);
    if ($this->form_validation->run() == FALSE)
1
Do you want a single custom validation message for the entire set of rules? - Yan Berk
@Yan Yes you are right. One message for each field - aWebDeveloper

1 Answers

0
votes

If you want a message for each rule, you could make a new array with the rules as key.

            $validationMessages = array('min_length' => 'String not long enough', 'max_length' => 'String too long');
            $this->addMessage($field, $validationMessages[$key]);

'Field' represents the field where the validation error has occured, 'key' is the specific business rule where things have gone wrong. You could expand it by adding custom variables to the messages, to display more accurate messages:

            $validationMessages = array('min_length' => '{field} not long enough', 'max_length' => '{field} too long');
            $this->addMessage($field, str_replace('{field}', $field['label'], $validationMessages[$key]);