Dynamically switch error message to check?

With a new validator object - is it possible to replace a validation error in a validation rule? to not only return a static error message, but maybe some dynamically generated one?

public function validateLength($data) {
    ...
    $length = mb_strlen($data['name']);
    $this->validator()->getField('name')->setRule('validateLength', array('message' => $length . 'chars')); 
    ...
}

doesn't work, of course (too late, I think)

I want to actually return the length of the string (for example, you used 111 characters out of 100 allowed), but for this I would need to replace the message from the (custom) validation method

$this->validate['name']['validateLength']['message'] = $length . 'chars';

never worked until now. it will always return the previous (static) error message from the $ validate array

+5
source share
2 answers
public function customValidator($data) {
    ....
    if ($validates) {
        return true;
    } else { 
        return 'my new error message';
    }
}
+9
source

The following snippet should do the trick:

public function validateLength($data) {
    ...
    $length = mb_strlen($data['name']);
    $this->validator()->getField('name')->getRule('validateLength')->message = $length . 'chars';
    ...
}
+2

All Articles