0

There's a way to add custom error messages to CodeIgniter validation_errors();?

Example, if I wanted a field with a 123456 value, and the user inputs 12345 I'd want to set a message to say:

The number 6 is required!

And any other custom rules I may want to add. Like a specific pattern or any other things.

Sorry for my english.

1 Answer 1

2

Yes, that is possible.

Set rules with callback like,

$this->form_validation->set_rules('field_name', 'Number', 'callback_custom_validation');

and define callback in the same controller like,

public function custom_validation($str)
{
    if ($str != '123456')
    {
        $this->form_validation->set_message('field_name', 'The %s field requires 123456');
        return false;
    }
    else
    {
        return true;
    }
}

Display your errors in view with <?php echo form_error('field_name')?>

More info on callbacks here.

Sign up to request clarification or add additional context in comments.

1 Comment

I think the first argument of set_message() should be the name of the callback function. $this->form_validation->set_message('custom_validation', 'The %s field requires 123456');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.