5
votes

With the new validator object - is it possible to replace the validation error inside the validation rule triggered? to not only return the static error message but maybe some dynamically genereted one?

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

does not work, of course (too late I guess)

I want to actually return the lenght of the string (you used 111 chars from 100 allowed) for example - but for this I would need to be able to replace the message from inside the (custom) validation method

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

also never worked so far. it would always return the previous (static) error message from the $validate array

2
@ADmad's answer will do the trick and a +1 from me, but is it worth firing a server-side request for this? Why not a counter that shows the number of characters that are left while the users are typing them in and a client-side JavaScript validation to throw the error? This would look more user-friendly and reduce the number of requests made. - Borislav Sabev
somebody else asked me already the very same question. I do something way more complicated actually. Just tried to keep the example simple. Also, the main idea here is how to override the message, not what is validated. BUT if I actually wanted to do this, the answer to your question would be: absolutely yes. you can always additionally validate via JS, but you ALWAYS need the serverside validation on top (because JS could be disabled or not working). therefore the validation in PHP is an absolute must anyway. - mark

2 Answers

9
votes
public function customValidator($data) {
    ....
    if ($validates) {
        return true;
    } else { 
        return 'my new error message';
    }
}
2
votes

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';
    ...
}