5

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

mark
  • 21,691
  • 3
  • 49
  • 71
  • @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 Jul 16 '12 at 20:53
  • 1
    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 Jul 17 '12 at 07:35

2 Answers2

10
public function customValidator($data) {
    ....
    if ($validates) {
        return true;
    } else { 
        return 'my new error message';
    }
}
ADmad
  • 8,102
  • 16
  • 18
  • Is the message detected by i18n console task when producing pot files or does one need to use __() explicitly ? – savedario Dec 18 '15 at 03:01
2

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';
    ...
}
dhofstet
  • 9,934
  • 1
  • 36
  • 37
  • Does the validation rule named "validateLength" exist in your $validate array, i.e. `$this->validator()->getField('name')->getRule('validateLength')` returns an object? – dhofstet Jul 16 '12 at 12:42
  • you were right all along! with all those tests the rule name was slightly changed when I tried your solution. thanks a lot! it works :) – mark Jul 16 '12 at 12:46