我想验证变量是数组还是匹配正则表达式的字符串.可以这样使用Laravel验证一个规则来完成?
这是我想要的示例:
// Does not work because the validation tries to match ALL conditions
$rules = [
'keys' => 'array|regex:\d+'
];
$validation = Validator::make(['keys' => '12345'], $rules);
if ($validation->fails()) {
// This is getting executed because it is not an array
} else {
// Do something else
}
通过使用2个不同的验证器对象(每个带有一个条件)并检查它们中的一个是否通过,我已经有了一种解决方法,但是我想知道Laravel中是否内置了更“优雅”的解决方案.
解决方法:
我能想到的最“优雅”的解决方法是创建Custom Validation Rule,但您也可以尝试conditionally adding the array and the regex rules.
但是,显而易见的是,检查变量的类型以添加适当的规则呢?
//dummy data, could be from $request->all()
$data = ['keys' => '12345'];
$rules = [
'keys' => is_array($data['keys']) ? 'array' : 'regex:\d+'
];
$validation = Validator::make($data, $rules);
快速简单,但是浪费了数组检查的时间,并且总是会给出正则表达式错误消息.