代码之家  ›  专栏  ›  技术社区  ›  Blues Clues

laravel中数组验证下的验证

  •  2
  • Blues Clues  · 技术社区  · 6 年前

    如果我有一个数组验证规则,如何检查数组中的所有项是否都是有效的电子邮件?我用这个: https://laravel.com/docs/5.1/validation#rule-array

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

    更新 -按要求。

    enter image description here

    2 回复  |  直到 6 年前
        1
  •  2
  •   Mohammad    6 年前

    检查是否验证:

    5.2以上

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

    或者

    小于5.2

        $validator = \Validator::make($request->all(), [
            'email' => 'array',
    
            /* Other rules */
    
        ],[
            'email.required' => 'message required',
            'email.array' => 'message array',
            'email.email' => 'message email',
        ]);
    
        $validator->each('email', 'required|email');
    
        if($validator->fails()) 
            return back()->withErrors($validator->errors());
    
    
        dd('Success All Email ;)');
    
        2
  •  1
  •   syam    6 年前

    你需要自定义验证器。在拉威尔的请求中,你可以这样做

    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;
        });
    }
    
    public function rules() {
        return [
            'email' => 'required|emails'
        ];
    }
    

    验证laravel 5.2以后的阵列:

    $validator = Validator::make($request->all(), [
        'person.*.email' => 'email|unique:users',
        'person.*.first_name' => 'required_with:person.*.last_name',
    ]);
    

    'custom' => [
        'person.*.email' => [
            'unique' => 'Each person must have a unique e-mail address',
        ]
    ],
    

    希望这对你有帮助。