somnambulist-tech / validation

A re-write of rakit/validation, a standalone validation library inspired by Laravel Validation
MIT License
44 stars 13 forks source link

Returning message strings from callbacks does not seem to work #26

Closed jakewhiteley closed 5 months ago

jakewhiteley commented 6 months ago

Conisider the following code:

<?php

require('vendor/autoload.php');

use Somnambulist\Components\Validation\Factory;

$testData = [
    'name' => 'John Doe',
    'custom' => 'foo'
];

$validation = (new Factory)->make($testData, [
    'name' => 'required',
    'custom' => [
        'required',
        function($value) {
            if ($value !== 'bar') {
                return ':attribute should be bar';
            }

            return true;
        }
    ]
]);

$validation->validate();

if ($validation->fails()) {
    // handling errors
    $errors = $validation->errors();
    echo "<pre>";
    print_r($errors->firstOfAll());
    echo "</pre>";
    exit;
} else {
    // validation passes
    echo "Success!";
}

The expected output would be an array with 1 error: "custom should be bar".

What actually happens is the following Fatal error is thrown: Somnambulist\Components\Validation\Exceptions\MessageException: No message was found for the language "en" and any of: "custom:callback", "custom", ":attribute should be bar"

What is the work-around for this?

jakewhiteley commented 5 months ago

@dave-redfern I don't suppose you have time to assist with this?

dave-redfern commented 5 months ago

@jakewhiteley You may have found a bug. I will try to look at it today, but I cannot guarantee that. In the meantime: you can add a custom message to the factory messages using the custom:callback key where custom is whatever the attribute name is that you have the rule on. That way it will work now while I look into it.

dave-redfern commented 5 months ago

@jakewhiteley I've pushed an update and tagged 1.9.1 as a release. This should fix the issue. Incidentally this actually highlighted another bug, so I fixed that too.

Could you please confirm if 1.9.1 fixes things for you?

jakewhiteley commented 5 months ago

@dave-redfern I will test today 👍 Thanks for the speedy response!

jakewhiteley commented 5 months ago

@dave-redfern All good, works as expected 💪