2

I can't validate a field, which contains array elements, in Form Request class. Rules method:

public function rules()
{
    return [
        "state" => 'required',
        "state.0" => 'required',
        "state.*" => 'required',
    ];
}

There is an array in request->all()

"state" => array:1 [
  0 => ""
]

Zero element is empty. But validation is successful. What am I doing wrong?

4
  • 1
    It's empty but it exists. What happens if you add "state.0" => 'required|min:1'? Commented Jul 20, 2017 at 14:36
  • Are you calling the rules into your controller and outputting an error message if it fails to pass? Commented Jul 20, 2017 at 14:37
  • @Mjh, required should be more than enough to not allow an empty field to pass through. Commented Jul 20, 2017 at 14:37
  • What version of laravel is this? Commented Jul 20, 2017 at 14:56

1 Answer 1

1

In order to handle the dynamic fields, you will need to loop through all the posted "items" and add a rule for each.
Here is an updated method demonstrating this:

public function rules() {
    $rules = [
          'state' => 'required',
         ];
    foreach($this->request->get('state') as $key => $val) {
        $rules['state.'.$key] = 'required';
    }
    return $rules;
}
Sign up to request clarification or add additional context in comments.

Comments

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.