1

If use_shipping is un-checked and user did not enter the value in the shipping_note - validation should have passed but it has failed?

<input type="hidden" name="use_shipping" value="0">
<input type="checkbox" name="use_shipping" value="1" {{ old('use_shipping', $delivery->use_shipping) ? 'checked="checked"' : '' }}>

Text

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

In Laravel request class:

public function rules()
{

    return [
        'use_shipping'  => 'boolean',
        'shipping_note' => 'required_with:use_shipping',
    ];
}
2
  • What error message did it give you? Did it tell you why it failed? Commented Jan 25, 2017 at 17:19
  • The error message I get telling me to enter the shipping_note when use_shipping is not ticked Commented Jan 25, 2017 at 17:23

1 Answer 1

5

The required_with validation states:

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

Because of your hidden input, the shipping_note field will always be present. Since the field is present even when the checkbox is unchecked, the required_with validation will always be triggered.

Most likely what you're looking for is the required_if validation, which states:

required_if:anotherfield,value,...

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

public function rules()
{
    return [
        'use_shipping'  => 'boolean',
        'shipping_note' => 'required_if:use_shipping,1',
    ];
}

This should cause shipping_note to only be required when the value of use_shipping is 1, which should only happen when the checkbox is checked.

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

3 Comments

Thank you for answer. Unfortunately 'required_if:use_shipping,1', does not work. Still same behaviour as before.
@I'll-Be-Back Are you sure? I just tested Validator::make(['use_shipping' => '0', 'shipping_note' => ''], ['use_shipping' => 'boolean', 'shipping_note' => 'required_if:use_shipping,1'])->passes(), and it returns true (validation passes).
Sorry, I have tested on wrong page - it is working indeed, thank you :)

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.