Home > Back-end >  Laravel at least one field is valid
Laravel at least one field is valid

Time:09-14

I have an array with two relevant keys where at least one of both shall contain a valid email address.

$data = [
 'mail' => 'firstname.lastname#tld.com',
 'mail2' => '[email protected]',
 ...
]

I've tried a validation using the exclude_with method, which works if the mail field is invalid, but mail2 is valid. However, it doesn't vice versa.

$validated = Validator::make($data, [
    'mail' => 'exclude_with:mail|email',
    'mail2' => 'exclude_with:mail2|email',
])->validate();

I could do this easily with other PHP methods or regular expressions, but I wonder if this is archivable with Laravel's validator.

The goal is to get at least one field with a valid email or fail.

CodePudding user response:

Use enter image description here

  • Both invalid emails

     $data = [
         'mail' => 'firstname.lastname#tld.com', // wrong 
         'mail2' => 'firstname.lastname#tld.com' // wrong 
     ];
    
     $validator = Validator::make($data, [
         'mail' => 'exclude_unless:mail2,null|email',
         'mail2' => 'exclude_unless:mail,null|email',
     ]);
    
     if ($validator->fails()) {
         $messages = $validator->messages();
         foreach ($messages->all() as $message)
         {
             echo $message;
         }
         die();
     }
     echo "pass";
     die();
    

    Output

    enter image description here


  • customize the error message to a standard message such as "At least one Email should be valid".

    • Related