0

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?

  • Try to put your custom rule validation in array like this: `'social_links.fb' => [new SocialFieldValidation($fieldDataFb)]` – Jérôme Mar 28 '22 at 20:58
  • So it works but only if I put already content there but I need to get there also if content is missing, means null – Marc Sinili Mar 28 '22 at 21:03
  • Solved, you should place "required" and in 3th paramter of $this->validate() place custom message string, more info at: https://stackoverflow.com/questions/45007905/custom-laravel-validation-messages#answer-62172386 – Marc Sinili Mar 28 '22 at 21:33
  • Show us your `app\Rules\SocialFieldValidation.php` class logic/source code. – steven7mwesigwa Mar 29 '22 at 02:04

1 Answers1

0

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:

Jérôme
  • 978
  • 1
  • 9
  • 22