2

My view blade like this :

...
<div class="checkbox">
    <label>
        {{Form::checkbox('is_anonymous', 1, false)}} As anonymous
    </label>
    @if ($errors->has('is_anonymous'))
        <div class="help-block">
            <strong>{{ $errors->first('is_anonymous') }}</strong>
        </div>
    @endif
</div>
<div class="checkbox">
    <label>
        {{Form::checkbox('term', 1, false, array('id'=>'term'))}} I aggree
    </label>
    @if ($errors->has('term'))
        <div class="help-block">
            <strong>{{ $errors->first('term') }}</strong>
        </div>
    @endif
</div>

My validation like this :

public function rules()
{
    return [
        'is_anonymous' =>'required',
        'term' =>'required'
        ...
    ];
}

If the code executed, the validation not work

There does not appear a message. Whether on the checkbox the validation process is different?

How can I solve this problem?

moses toh
  • 12,344
  • 71
  • 243
  • 443
  • Please follow this link(https://stackoverflow.com/questions/37345363/laravel-validation-checkbox) hope this work for you – AddWeb Solution Pvt Ltd Aug 31 '17 at 10:50
  • @AddWeb Solution Pvt Ltd, I had see the link. But it did not help me. My problem is I have 2 checkbox – moses toh Aug 31 '17 at 14:47
  • Wait i will check it – AddWeb Solution Pvt Ltd Aug 31 '17 at 14:48
  • It will work, just be sure the input value will not be an empty string or false. And 'checkbox' =>'required' is ok as long as the key is the value of the input name attribute – AddWeb Solution Pvt Ltd Aug 31 '17 at 14:49
  • @AddWeb Solution Pvt Ltd, On the checkbox, if not checked, the value does not exist. So because the value does not exist, then the validation not display – moses toh Aug 31 '17 at 14:55
  • Just to double check, am I right in saying that if the checkbox isn't the validation passes i.e. the code in your `Route`/Controller method gets executed? Is the validation not passing even if the checkbox is checked? – Rwd Sep 02 '17 at 08:51

2 Answers2

1

You can replace your required rule with accepted when dealing with checkboxes.

As stated from the docs:

The field under validation must be yes, on, 1, or true. This is useful for validating "Terms of Service" acceptance.

plmrlnsnts
  • 1,644
  • 12
  • 10
0

I came across this problem. I think it occurs because when a checkbox is not checked, it won't be included in the request. And if is not included in the request, Laravel will not try to validate it.

My solution was to add a hidden input with a default value before the actual checkbox.

{{Form::hidden('term', false)}}
{{Form::checkbox('term', 1, false, array('id'=>'term'))}} I aggree

Here is a related question about this behaviour.

Camilo
  • 6,504
  • 4
  • 39
  • 60