php - Laravel 验证条件
问题描述
我正在尝试验证我的领域。如果 is_teacher 为 false,teacher_id 为空。然后我会抛出错误信息。但我不确定为什么即使 is_teacher 字段为真,它们也会提示此错误消息。假设 is_teacher 为真,则无需输入此条件。
if(is_bool($input['is_teacher']) == false && empty($input['teacher_id'])) {
$validator->errors()->add('teacher_id', 'Please select a teacher.');
return response()->json([
'error' => true,
'messages' => $validator->errors(),
], 422);
}
解决方案
is_bool
检查变量是否为布尔值。变量必须是true
或false
例如
$input=['is_teacher'=>true];
dd(is_bool($input['is_teacher']));
这将返回 true ;
$input=['is_teacher'=>12];
dd(is_bool($input['is_teacher']));
这将返回错误。
如果你看到下面的函数,那么你可以看到 is_bool 到底会做什么
/**
* Finds out whether a variable is a boolean
* @link http://php.net/manual/en/function.is-bool.php
* @param mixed $var <p>
* The variable being evaluated.
* </p>
* @return bool true if var is a boolean,
* false otherwise.
* @since 4.0
* @since 5.0
*/
function is_bool ($var) {}
欲了解更多信息:https ://www.php.net/manual/en/function.is-bool.php
更新
$input=[
'is_teacher'=>0,
'teacher_id'=>""
];
$validator = Validator::make($input, [
'teacher_id' => Rule::requiredIf(function () use ($input) {
return !$input['is_teacher'] && empty($input['teacher_id']);
}),
],[
'teacher_id.required'=>'Please select a teacher.'
]);
if ($validator->fails()) {
return response()->json([
'error' => true,
'messages' => $validator->errors(),
], 422);
}
您可以像下面这样导入验证和规则
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
回应将是
{
"error": true,
"messages": {
"teacher_id": [
"Please select a teacher."
]
}
}
推荐阅读
- android - 迁移到 AndroidX 后的 SingleLiveEvent 问题
- javascript - 如果我浅合并两个相同的对象,使用哪个对象的引用?
- reactjs - React 的响应式边距
- java - 如何根据用户定义的参数执行节流?
- python - 如果列表元素属于某种类型,则遍历列表并打印“真”
- ruby-on-rails - Rails 5范围像多个部分字符串
- javascript - 多步表单Javascript
- php - SQL 语句参数与我的变量匹配,但我不断收到错误消息
- python - Django 全局覆盖 slugify
- python - AttributeError:类型对象“DirectView”没有属性“as_view”