使用自定义验证显示所有无效邮件

时间:2015-08-05 08:04:00

标签: php laravel laravel-5 laravel-5.1

我已经创建了一个自定义验证请求,可以在一个输入中读取多个电子邮件地址。

CustomRequest

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

示例输入:

test
test.q
test@test.com

由于上述输入无效,因此会显示以下错误:

One of the emails must be a valid email address.

目前上面的代码正在运行,但我想要的是显示每个无效的电子邮件。 E.g

test is an invalid email
test.q is an invalid email

我该怎么做?请帮忙。感谢

1 个答案:

答案 0 :(得分:1)

这是我现在的代码。

public function __construct(Factory $factory)
{
    \Session::forget('invalid_emails');
    $factory->extend("emails", function($attribute, $value, $parameters)
    {
        $rules = [
            'email' => 'required|email',
        ];
        $emailArr = explode("\r\n", $value);
        $emailArr = array_filter($emailArr, 'trim');
        $invalidEmails = [];
        foreach ($emailArr as $key => $email) {
            $data = [
                'email' => $email
            ];
            $validator = \Validator::make($data, $rules);
            if ($validator->fails()) {
                $invalidEmails[] = $email;
            }
        }

        if (arrayHasValue($invalidEmails)) {
            $errorMsg = implode(',', $invalidEmails);
            \Session::put('invalid_emails', $errorMsg);
            return redirect()->route('invitation')
                ->withErrors( ['emails' => trans('validation.emails', ['attribute' => $errorMsg])] )
                ->withInput();
        }

        return true;
    });
}

然后在你的控制器方法中,你只需要在输入一些逻辑等之前检查会话密钥email_invalid ......

我知道它有点乱,我愿意接受建议:)