【发布时间】:2021-07-09 14:09:37
【问题描述】:
我有一个select 下拉列表,其中包含来自数据库表options 的选项。值如下:
cheese
pepper
onions
other
选项"other" 不在数据库中,但是当用户选择该选项时,他们可以输入新选项。我想验证输入,以便options 表中的选项exists 或值"other"。如何创建这样的验证?
【问题讨论】:
标签: laravel validation
我有一个select 下拉列表,其中包含来自数据库表options 的选项。值如下:
cheese
pepper
onions
other
选项"other" 不在数据库中,但是当用户选择该选项时,他们可以输入新选项。我想验证输入,以便options 表中的选项exists 或值"other"。如何创建这样的验证?
【问题讨论】:
标签: laravel validation
运行命令来创建自定义规则。它将在规则文件夹中创建一个文件。
php artisan make: rule CheckExistance
然后像下面这样更新这个文件的功能:
public function passes($attribute, $value){
$optionExist=Option::where('option_name',$value)->exists();
if ($optionExist|| $value=="other") {
return true;
}
}
并打印如下错误:
public function message(){
return 'The :attribute already exists.';
}
最后在控制器中使用验证,如下所示:
$request->validate([
'inputName'=>['required', new CheckExistance()],
]);
【讨论】:
CheckExistenceOrOther 函数,我们可以在其中传入模型/数据库表,它会检查吗?
Option:: 如果是不同的模型,则需要更改。