Conditional Validation If Checkbox Selected Laravel

I have a form in Laravel in which I want to validate three text fields based on a checkbox. Its an edit user form in which I only want to update the password if I select yes. This is the form in my view:

<section>
    <div class="form">
        <h1>Edit: {!! $user->name !!}</h1>
        {!! Form::model($user, ['method' => 'PATCH', 'action' => ['AccountController@update', $user->id], 'files' => true]) !!}
        <p>Name: {!! Form::text('name') !!}
        <p>Email: {!! Form::text('email') !!}
        <p>Update Password? (tick for yes) &nbsp; {!! Form::checkbox('updatepasswordcheck', 0, false) !!}
        <p>Old Password: {!! Form::password('oldpassword') !!} 
        <p>New Password: {!! Form::password('newpassword') !!}
        <p>New Password Confirm: {!! Form::password('newpasswordconfirm') !!}
        @if($user->role_id == 1) 
            <p>User Role: {!! Form::select('user_type', ['admin', 'guest'], '1') !!}
        @else
            <p> User Role: {!! Form::select('user_type', ['admin', 'guest'], '0') !!}
        @endif
        <p>{!! Form::submit('Update') !!}
        {!! Form::close() !!}
        @include ('errors.list_errors')
    </div>
</section>

I then have a request called EditAccountRequest like so:

<?php

namespace App\Http\Requests;

use App\Http\Requests\Request;

class EditAccountRequest extends Request
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
      

        if($this->inputs['updatepasswordcheck'])
        {
            $rules['oldpassword'] = 'required';
            $rules['newpassword'] = 'required';
            $rules['newpasswordconfirm'] = 'required';  
        }
        $rules['name'] = 'required|min:3';
        $rules['email'] = 'required|email';
        
        return $rules;
    }
}

My problem is that when I see if the checkbox 'updatepasswordcheck' is true it never works because the input always appears as null. Anyone know how to fix this?

5 Answers

Ok I worked it out. I did this and it works:

public function rules()
{
        if($this->has('updatepasswordcheck'))
        {
            $rules['oldpassword'] = 'required';
            $rules['newpassword'] = 'required';
            $rules['newpasswordconfirm'] = 'required';  
        }
        $rules['name'] = 'required|min:3';
        $rules['email'] = 'required|email';

        return $rules;
}

I'm using Laravel 5.5 and this code works fine, my scenario was if "Company Info" drop-down selected "Yes" then "Company Name" should be required.

Controller:

protected function validator(array $data)
{
   return Validator::make($data, [

      'company_name' => 'required_if:is_company,1',

   ]);
}

View:

<label class="control-label">Company Info</label>
<select id="is_company" class="form-control" name="is_company">
       <option value="0">No</option>
       <option value="1">Yes</option>
</select>


<label class="control-label">Company Name</label>
<input type="text" class="form-control" name="company_name">

More Detail

1

You could do the following in this example:

public function rules(Request $request)
{
    if($request->has('updatepasswordcheck'))
    {
        $rules['oldpassword'] = 'required';
        $rules['newpassword'] = 'required';
        $rules['newpasswordconfirm'] = 'required';  
    }
    $rules['name'] = 'required|min:3';
    $rules['email'] = 'required|email';

    return $rules;
}
4

A cleaner and straight forward solution

    $validated = $request->validate([
        .
        .
        .
        'newpasswordconfirm' => 'required|accepted',
        'oldpassword' => 'required',
        'newpassword' => $request->newpasswordconfirm === 'yes' ? 'required': 'nullable',
    ]);

may be can use required_unless for this purpose:

$this->validate($request, 
        [
            'content' => 'required_unless:otherfields,null',
        ],
        [
            'content.required_unless' => 'Please enter content for detail'
        ]);

Documentation:

there is another way to Take a look at the sometimes rule. This will run the rule only when the field is available:

Documentation:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Maya Lin-Takahashi

Maya Lin-Takahashi

Consumer Tech & Gadget Reviewer

Maya is a hardware enthusiast who tests and reviews smart home devices, smartphones, wearables, and audio gear. She focuses on practical consumer value and build quality.

Share this article
Twitter Facebook Pinterest