'Laravel, use only custom rule class for validation?

I have some dynamic fields and can't use usual field validation. My question is, how can I use only my custom rule class without defining if it's required or not?

This doesn't work:

$this->validate($request, [
            'social_links.fb' => new SocialFieldValidation($fieldDataFb),
            'social_links.linkedin' => new SocialFieldValidation($fieldDataLinkedIn),
            'social_links.twitter' => new SocialFieldValidation($fieldDataTwitter)
        ]);

To get this work I need to add something like:

$this->validate($request, [
            'social_links.fb' => ['sometimes', new SocialFieldValidation($fieldDataFb)],
            'social_links.linkedin' => ['sometimes', new SocialFieldValidation($fieldDataLinkedIn)],
            'social_links.twitter' => ['sometimes', new SocialFieldValidation($fieldDataTwitter)]
        ]);

To use always validation class I need to set required or sometimes but I would need only to use validation class without other definitions, is that possible?



Solution 1:[1]

As mentionned in your comment, if putting your custom rule validation in array works but you want this working in case of null value, then you need to do use the nullable validation:

$this->validate($request, [
     'social_links.fb' => ['nullable', new SocialFieldValidation($fieldDataFb)],
     'social_links.linkedin' => ['nullable', new SocialFieldValidation($fieldDataLinkedIn)],
     'social_links.twitter' => ['nullable', new SocialFieldValidation($fieldDataTwitter)]
]);

If you need the documentation:

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jérôme