1

Lets say I submit this form:

<form>
    <input type="text" name="emails[]">
    <input type="text" name="emails[]">
    <input type="text" name="emails[]">
    <input type="text" name="emails[]">
    <input type="text" name="emails[]">
</form>

How do I then validate that at least one (anyone) of the $request->emails[] is filled?

I have tried this - however it does not work:

 $request->validate([
     'emails' => 'array|min:1',
     'emails.*' => 'nullable|email',
 ]);

Laravel 7

2 Answers 2

2

Try this

$request->validate([
    'emails' => 'array|required',
    'emails.*' => 'email',
]);

Cordially

Sign up to request clarification or add additional context in comments.

2 Comments

Nope - it "requires" all fields to be set.
wich field are you talking ? I can see only one email field in your form.
1

To meet your requirement, you may need custom rule

First create a rule, php artisan make:rule YourRuleName

inside YourRuleName.php

 public function passes($attribute, $value)
 {
     foreach(request()->{$attribute} as $email) {
         // if not null, then just return true. 
         // its assume in arrays some item have values
         if ($email) { // use your own LOGIC here
             return true;
         }
     }

     return false;
 }

Then,

 $request->validate([
     'emails' => [new YourRuleName],
 ]);

3 Comments

if($email) will not give correct results if the user passes spaces as value
its just example tho.. replace with your logic in that..
Thanks @ZeroOne. The final solution as above + 'candidate_email' => [new MinOneArrayFilled], 'candidate_email.*' => ['email', 'nullable']

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.