0

I am attempting to validate the values of a multiple select form using the IN validation rule. I continue to get the error that my value is incorrect despite being identical to one of the options in the list. I am thinking it has to be the way I am identifying the name in the validator ("step1"). However, I have also used step1., step1.0., step1*. It will keep giving the "Invalid Response" response which corresponds to the IN error.

Controller

public function postQuestionDetailsStep1(Request $request)
{
    if ($request->ajax())
    {
        $step1 = $request->input('step1');

        $this->validate($request, [
            'step1' => 'required',
            'step1.0' => 'in:Less than $50,000,$50,000-$100,000,More than $100,000',
        ], [
            'step1.required' => 'You must choose one.',
            'step1.in' => 'Invalid response.',
        ]);
    }
}

View

<input type="checkbox" class="custom-control-input" id="step1-option1" name="step1[]" value="Less than $50,000">
<input type="checkbox" class="custom-control-input" id="step1-option2" name="step1[]" value="$50,000-$100,000">
<input type="checkbox" class="custom-control-input" id="step1-option3" name="step1[]" value="More than $100,000">

Javascript

$('#step-1').submit(function(e) {
    e.preventDefault();

    var step1 = [];

    $("input[name='step1[]']:checked").each(function() {            
        step1.push($(this).val());
    });

    $.ajax({
        type: "POST",
        url: "/question/details/1",
        data: {step1:step1},
        error: function(data){
        },
        success: function(data) {
            console.log(data);
        }
    });
});
3
  • What version of Laravel are you using? Commented Oct 2, 2018 at 13:09
  • 5.6, I believe...... Commented Oct 2, 2018 at 13:10
  • 2
    Since your rule options also have comma, have you try using double quote: in:"Less than $50,000","$50,000-$100,000","More than $100,000"? Reference: stackoverflow.com/questions/19575860/… Commented Oct 2, 2018 at 13:17

1 Answer 1

1

The comma's in your in rule, mess up the array you are trying to create. Laravel will read your array like this:

['Less than $50', '000', '$50', '000-$100', '000', 'More than $100', '000']

You can change the rule to the following, to solve the problem you have with the comma's:

in:Less than $50,000,$50,000-$100,000,More than $100,000'

to

Rule::in(['Less than $50,000', '$50,000-$100,000', 'More than $100,000']);

Make sure to use the Rule class:

use Illuminate\Validation\Rule;
Sign up to request clarification or add additional context in comments.

1 Comment

It threw me off to use the Rule class in the validation like that. This works, however. 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.