【发布时间】:2020-06-12 08:26:21
【问题描述】:
【问题讨论】:
-
您可以将 onclick 的事件处理程序放在复选框上,并且无论何时运行事件处理程序,您都可以在 if 语句中检查复选框是否被勾选,然后从那里将输入设置为您需要的任何值。
标签: javascript php laravel bootstrap-4
【问题讨论】:
标签: javascript php laravel bootstrap-4
后端验证
你可以使用required_ifLaravel 验证规则
$validator = Validator::make($request->all(), [
'checkbox_field' => 'required|boolean',
'otherField' => 'required_if:checkbox_field,1',
// same for other fields
]);
if ($validator->fails()) {
dd('Validation Error.', $validator->errors());
}
$validatedData = $validator->validated();
前端验证
您也可以使用 jQuery 添加所需的约束
$('#myCheckBoxId').change(function() {
if($(this).is(':checked')) {
console.log("Checked");
$("#myInput1ID").prop('required',true);
$("#myInput2ID").prop('required',true);
//...
} else {
console.log("Unchecked");
$("#myInput1ID").removeAttr('required');
$("#myInput2ID").removeAttr('required');
//...
}
});
检查工作Demo
【讨论】:
Laravel 有一个很棒的表单请求验证系统。我强烈建议使用它而不是在控制器中使用所有验证逻辑。
使用以下命令使用工匠控制台创建请求;
php artisan make:request PageRequest
它将创建一个扩展 Illuminate\Foundation\Http\FormRequest; 的 PageRequest 类
看起来像这样;
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize(): bool
{
return true; // you can use custom auth logic
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules(): array
{
$rules = [
'title' => 'required|numeric', // default inputs
];
// optional inputs
if ($this->has('post_image'))
$rules['post_image'] = 'required|image|max:500|mimes:jpg,jpeg,gif';
}
}
return $rules;
}
/**
* Set the validation attributes
*
* @return array
*/
public function attributes(): array
{
// you can use laravel's language system or just strings
return [
'title' => trans('web.forms.title'),
'post_image' => trans('web.forms.post_image'),
];
}
然后你可以像这样在资源控制器中注入你的请求;
public function store(PageRequest $request, $id) {}
Laravel 文档Form Request Validation
【讨论】:
发送表单后,您可以在控制器中这样做:
public function sendForm (Request $request){
if($request->checkbox == "checked"){
$request->validate([
//Your validation rules.
]);
}
}
【讨论】: