Search code examples
laravelvalidationlaravel-validation

Laravel Rules Validation - Only another field has a value


<input type="checkbox" name="grievance_discipline" value="checked">
<select name="grievance_type">
<option value="_none" selected>- Select One</option>
<option value="suspension">Suspension</option>
</select>

<?php

$this->validate($request,[
  'grievance_type' => 'required_if:grievance_discipline, checked|not_in:_none',
]);

?>

The trouble I am running in to, is telling Laravel to ONLY use a particular validation rule if another field has a value.

In the example, the discipline_type field (a select list), is required IF grievance_discipline is checked.

The default select option for the select list is - Select One - with the value of _none. In the validation rules, _none should be thrown out, but it should ONLY validate on it if the grievance_discipline checkbox has value 'checked'.

Could anybody help me with this, please?


Solution

  • How about setting the first option as disabled so the user are forced to pick a value or not submitting a value, hence gracefully fail your validation check. Also, use required_with instead of required_if to check if another value exist or not.

    <input type="checkbox" name="grievance_discipline" value="checked">
      <select name="grievance_type">
      <option disabled selected value>- Select One</option>
      <option value="suspension">Suspension</option>
    </select>
    

    Then in the PHP, do

    $this->validate($request,[
        'grievance_type' => 'required_with:grievance_discipline'
    ]);