0

I have form where I can add up to 30 option fields (option[1], option[2], ...) and for now Im using 'option.*' => 'required' rule in request validation but with this there is a little problem, if you submit form with all option fields empty it shows long error message with each option field required, but I need that it shows only one message for all options like: "Each option field is required".

Any ideas how to make it? Thanks!

3
  • set custom message for this field? Commented Mar 14, 2016 at 21:28
  • you mean each select field is required? Do you only have one select with 30 options or 30 select fields? Commented Mar 14, 2016 at 21:29
  • They are not selects, but text inputs (can add up to 30) and all of them are required but I need to return only one message not 30x same message. Commented Mar 16, 2016 at 2:50

1 Answer 1

2

I found a solution to this. I will post it here in case somebody needs it:

Basically, you need to override formatErrors method in your request validation class

protected function formatErrors(Validator $validator)
{
    $errors = parent::formatErrors($validator);

    // this will remove the keys that have index larger than 0
    $keys = array_filter(array_keys($errors), function($item) {
        $parts = explode('.', $item);

        // you might want to modify this to match your fields, 
        // I had another level of keys
        if (count($parts) === 3 and is_numeric($parts[1]) and (int)$parts[1] > 0) {
            return false;
        }

        return true;
    });

    $errors = array_intersect_key($errors, array_flip($keys));

    return $errors;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Can you explain how to use the above method in request validation class?

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.