Cristian Bustos
Cristian Bustos

Reputation: 369

Validate multiple emails in a single text field using Laravel?

How can I validate that multiple is correct in a text field using Laravel?

Example 1:

The 3 emails are fine, therefore it return true

enter image description here

Example 2:

The first 2 emails are fine, but 3 is incorrect return false

enter image description here

For now, only the code that validates a single email

public function rules()
{
   return [
      'emails' => 'required|email'
   ];
}

Thanks.

PS: The number of emails can vary (1 to N)

Upvotes: 3

Views: 2178

Answers (3)

Erubiel
Erubiel

Reputation: 2972

How are you posting the request?

If you are using javascript/ajax you can split the email field before sending and put it into three different fields like email[].

Then in your controller you can do something like

    $validator = Validator::make($request->all(), [
        'email.*' => 'required|email',
    ],[
        'email.*.email' => 'In case you are wondering how to set error messages for this kind of validation'
    ]);

If you are not using Javascript, you may consider using more than one field or writing some custom validation as suggested by @TobiasK

Upvotes: 0

Stephan de Souza
Stephan de Souza

Reputation: 46

Extend a new validator called "emails" that explodes your value and validate each email separately.

A fine solution can be find here: https://stackoverflow.com/a/29455516/405217

Upvotes: 2

Zakaria Acharki
Zakaria Acharki

Reputation: 67505

You could use regex validation in this case :

public function rules()
{
   return [
      'emails' => ['required','regex:/^(\s?[^\s,]+@[^\s,]+\.[^\s,]+\s?)*(\s?[^\s,]+@[^\s,]+\.[^\s,]+)$/g']
   ];
}

Upvotes: 1

Related Questions