Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Validation If checkbox ticked then Input text is required?

I have been reading Laravel validation documentation. I am not clear how to combine two rules.

For example:

<input type="checkbox" name="has_login" value="1">

<input type="text" name="pin" value="">

If has_login checkbox is ticked then Input text pin value is required.

If has_login is not ticked then Input text pin is not required.

Laravel Validation:

public function rules()
{
    return [
          'has_login' => 'accepted',
          'pin' => 'required',
    ];
}
like image 479
I'll-Be-Back Avatar asked Jul 22 '16 11:07

I'll-Be-Back


1 Answers

Use required_with or required_if

required_with:foo,bar

The field under validation must be present and not empty only if any of the other specified fields are present.

return [
      'has_login' => 'sometimes',
      'pin'       => 'required_with:has_login,on',
];

--

required_if:anotherfield,value

The field under validation must be present and not empty if the anotherfield field is equal to any value.

return [
      'has_login' => 'sometimes',
      'pin'       => 'required_if:has_login,on',
];

--

https://laravel.com/docs/5.2/validation

--

Also, if the checkbox has_login is not checked, it will not send as part of the form submission

like image 144
H H Avatar answered Sep 29 '22 00:09

H H