Home > Back-end >  only required if checkbox is checked else text field must be left empty laravel
only required if checkbox is checked else text field must be left empty laravel

Time:02-03

I understand the required_if. My issue is there is a checkbox or select where Other is checked or selected the Other Textfield is required. But is Other is not checked or selected that Particular Textfield should be empty. If it has anything is should give an error This Textfield Cannot must be blank since you did not select the option of others

CodePudding user response:

Try this on the request validation:

 'name_of_your_checkbox' => 'nullable'
 'name_of_your_textfield' => 'nullable|required_if:name_of_your_checkbox,checked'

CodePudding user response:

use required_if https://laravel.com/docs/8.x/validation#rule-required-if this is example

use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;

Validator::make($request->all(), [
    'role_id' => Rule::requiredIf($request->user()->is_admin),
]);

Validator::make($request->all(), [
    'role_id' => Rule::requiredIf(function () use ($request) {
        return $request->user()->is_admin;
    }),
]);
  •  Tags:  
  • Related