Why validation works wrong?

62 Views Asked by At

This is validation rule:

$validator = Validator::make($request->all(), [
            'email' => 'required|array',
            'email.*' => 'required|email'
        ]);

        if ($validator->fails()) {
            throw new ValidationException($validator);
        }

This data that with header: application/json, text/plain, */* Content-Type: application/json I send using client:

[{"email":"[email protected]"},{"email":"[email protected]"}]

Also I tried:

{"emails":["[email protected]"]}
2

There are 2 best solutions below

0
Erik On BEST ANSWER

Try to send it as array:

[{"email":["[email protected]","[email protected]"]}]
0
Harshad On

I think you should try below.

public function __construct() {
    Validator::extend("emails", function($attribute, $value, $parameters) {
        $rules = [
            'email' => 'required|email',
        ];
        foreach ($value as $email) {
            $data = [
                'email' => $email
            ];
            $validator = Validator::make($data, $rules);
            if ($validator->fails()) {
                return false;
            }
        }
        return true;
    });
}

In your function

$validator = Validator::make($request->all(), [
            'email' => 'required|emails'
        ]);

        if ($validator->fails()) {
            throw new ValidationException($validator);
        }

And send data like

{"email":["[email protected]","[email protected]"]}

I'm not tested it but this will helps you.