outl1ne / nova-translatable

A Laravel Nova package that allows you to make any input field translatable.
MIT License
196 stars 56 forks source link

Validation rules: "lighter" required #9

Open phlisg opened 4 years ago

phlisg commented 4 years ago

Hello,

Thank you for the package.

Testing around with it this morning, I found out that a field that has a required rule throws an error if not all translations have been set. How can I enforce a "lighter" requirement, such as: "required if 1 or more translations have been set"? Currently it's more: "all translations must be set".

Thank you for your help :-)

Tarpsvo commented 4 years ago

I need to think about it. I think this requires a very custom Laravel Validator rule.

phlisg commented 4 years ago

I was using https://github.com/mrmonat/nova-translatable beforehand and it didn't have this issue, but I prefer this package with its language handling and field compatibility :-)

phlisg commented 4 years ago

Hello @Tarpsvo

Just experimented this day with some simple rule, by using the resource's $request argument:

Text::make("Nom", 'name')
    ->translatable(Languages::all())
    ->rules('required_with', function($attribute, $value, $fail) {
       if (collect($this->request->get('name'))->values()->flatten()->filter()->count() === 0)
            return $fail("L'attribut {$attribute} ne peut être vide.");
        }),

This will check if any languages got filled or not, and will throw an error if it's definitely empty. Not the prettiest solution neither, but it works :D

Tarpsvo commented 4 years ago

Hi! I just released version 1.6.0 which has a new feature ->rulesFor() which should allow you to specify lighter rules.

phlisg commented 4 years ago

Hello @Tarpsvo

Thank you for your follow up and sorry for my slow answer.

Following the documentation you wrote, I'm not sure I grasped how it works:

TextCounted::make('Name', 'name')
        ->help("Le nom de l'offre")
        ->translatable(Languages::all())
        ->required()
        ->rulesFor('fr', [
            'required',
        ])
       ->sortable()),

If I leave the name.fr blank and fill something else I get no errors

Thank you for your help :)

JoanBonnin commented 4 years ago

@phlisg I was facing the same problem... But after surfing the source code I found the error.

Even you are setting the rule properly, the validation of that rules is done in the HandlesTranslatable trait. You could simply use the trait in your nova resource and it should work like a charm 😉

clementmas commented 2 years ago

I still can't find a way to mark a field as "at least one language is required".

->rules('required') requires filling in all the fields. ->rulesFor('en', ['required']) requires filling in a specific language.

Is it possible to require filling in at least one/any language?