Faust
Faust

Reputation: 93

Codeigniter form validation callback rule issue

I am using Codeigniter 3.x form validation callback method in combination trim and required to validate a field. The problem is, when I pipe them: trim|required|callback_some_method, the callback method seems to take precedence over trim and required and shows its error message. Any ideas on this?

EDIT: This is the rule:

$this->form_validation->set_rules('new_password', 'New Password', 'trim|required|min_length[8]|callback_password_check');

And this is the password_check method:

function password_check($pwd) {
    $containsLetterUC = preg_match('/[A-Z]/', $pwd);
    $containsLetterLC = preg_match('/[a-z]/', $pwd);
    $containsDigit = preg_match('/\d/', $pwd);
    $containsSpecial = preg_match('/[^a-zA-Z\d]/', $pwd);

    if ( !($containsLetterUC && $containsLetterLC && $containsDigit && $containsSpecial) ) {
        $this->form_validation->set_message('password_check', '{field} must contain UPPERCASE and lowercase letters, digits, and special characters.');
        return FALSE;
    }       

    return TRUE;
}

The method should return FALSE, but as long as required is before my custom rule and the field is empty, it should stop there with Required field message, NOT the custom method message.

Upvotes: 0

Views: 374

Answers (2)

b126
b126

Reputation: 1254

Unfortunately, as described in the code from CI, callbacks validation rules are always verified first, prior to ‘required’ for instance.

There is an official issue opened at CI : https://github.com/bcit-ci/CodeIgniter/issues/5077

Upvotes: 0

Faust
Faust

Reputation: 93

Okay guys, I've managed to solve it by extending the Form_validation library, putting my callback method there and piping as the other rules (without callback_ prefix).

Upvotes: 2

Related Questions