Dynamically switching the error message on validation?
Asked Answered
H

2

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

Haag answered 15/7, 2012 at 19:12 Comment(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.Paries
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.Haag
W
10
public function customValidator($data) {
    ....
    if ($validates) {
        return true;
    } else { 
        return 'my new error message';
    }
}
Wye answered 16/7, 2012 at 12:54 Comment(1)
Is the message detected by i18n console task when producing pot files or does one need to use __() explicitly ?Roseola
B
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';
    ...
}
Balkanize answered 16/7, 2012 at 5:19 Comment(2)
Does the validation rule named "validateLength" exist in your $validate array, i.e. $this->validator()->getField('name')->getRule('validateLength') returns an object?Balkanize
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 :)Haag

© 2022 - 2024 — McMap. All rights reserved.