valitron icon indicating copy to clipboard operation
valitron copied to clipboard

Repeat/echo the value of the failed rule in the error message?

Open RickKukiela opened this issue 1 year ago • 2 comments

I'm sorry if this is answered somewhere, I tried searching here and read the Readme twice, and analyzed the error method in the src and cannot figure out how to do this, or if it's even possible.

Currently I can repeat back the name of the field that failed its validation in the error message by using {field}, however for debugging purposes I was trying to add {value} and it does not work. I checked the error() method at runtime and the $values array that gets passed is empty so the $params array it creates for the vsprintf call is empty.

How can I write my rule so the $values param that is passed to the error method is populated?

Here is the code I am currently using:

        $this->validator->rule('required', 'primaryNtpServer');
        $this->validator->rule('optional', 'secondaryNtpServer');
        $this->validator->rule(function ($field, $value) {
            if ($field === 'secondaryNtpServer' && empty($value)) {
                return true;
            }
            return Services::dateTime()::verifyNtpdServer($value);
        }, ['primaryNtpServer', 'secondaryNtpServer'], [)->message('{field} "{value}" did not respond to an NTP request.');

RickKukiela avatar May 17 '24 16:05 RickKukiela

Hey homie, it may be too late, but vsprintf expects %s not {value}.

So to fix your issue, you would do: ->message('{field} "%s" did not respond to an NTP request.');

zwalden avatar Feb 06 '25 18:02 zwalden

@zwalden Thanks! Yeah I cant remember what I ended up doing here at this point, but I don't think I was able to test the value it was getting when I posted this.

While you're correct about how to format the message so the value would be printed (that was so obvious I feel dumb I didn't realize that until after reading your message), I wrote in the issue that the the array being passed to vsprintf was reported to be empty at runtime during an xdebug session. So I think that even if I had %s in the message, I'm not sure the value would have been printed in this case since the data I was looking to print out did not appear to be available.

I'll have to keep this in mind and try it the next time I'm messing about in that project to see if it makes any difference.

RickKukiela avatar Feb 06 '25 18:02 RickKukiela