Laravel中数组验证下的验证

时间:2018-09-17 06:42:42

标签: php laravel laravel-5

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

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

注意:我使用的是laravel 5.1版本

更新-根据请求。

enter image description here

2 个答案:

答案 0 :(得分:1)

检查是否有效:

  

高于5.2

class ExcelMacro(unittest.TestCase):
    def test_excel_macro(self):
        try:
            xlApp = win32com.client.DispatchEx('Excel.Application')
            xlsPath = os.path.expanduser(r"D:\Myfile.xlsm")
            wb = xlApp.Workbooks.Open(Filename=xlsPath)
            xlApp.Run('Foglio2.CATRun')
            wb.Save()
            xlApp.Quit()
            print("Macro ran successfully!")
        except:
            print("Error found while running the excel macro!")
            xlApp.Quit()
if __name__ == "__main__":
    unittest.main()

OR

  

小于5.2

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

答案 1 :(得分:1)

您需要自定义验证器。在Laravel Request中,您可以做类似的事情

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',
    ]
],

希望这对您有所帮助。