7

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',
    ];
}
0

1 Answer 1

18

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

Sign up to request clarification or add additional context in comments.

4 Comments

To improve your answer. You need provide example code rather then copy and paste from Doc.
@I'll-Be-Back added :)
@I'll-Be-Back not the docs, when I post checkbox values and see the data using $request->all(), if the checkbox is ticked, then the value is on, if not ticked then it doesn't appear in the submitted input array, if this is wrong please let me know and i will update my answer
Since in this question there is only 1 field that needs to be examined, a required_if is the best option.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.