2

I working on Laravel application. In UserRequest I am validating the input. The following rule:

'name' => 'sometimes|required|string|min:2|max:50'

fails if user name is not present although there is sometimes keyword present. The following request works fine though:

'name' => 'sometimes|string|min:2|max:50'

I am not the first one to experience this problem (see Laravel validation required rule not working).

However, documentation says that I should use the first option:

In some situations, you may wish to run validation checks against a field only if that field is present in the input array. To quickly accomplish this, add the sometimes rule to your rule list:

$v = Validator::make($data, [
    'email' => 'sometimes|required|email',
]);

In the example above, the email field will only be validated if it is present in the $data array.

(https://laravel.com/docs/5.1/validation)

Does some know if that something I am doing wrong or a bug that needs to be reported?

Community
  • 1
  • 1
Dmitry Torba
  • 3,004
  • 1
  • 14
  • 24
  • 1
    It's just an order of operations problem. In the 5.1 core there's an internal issue with an explode and glue. I'll save you the boring basics but `required` needs to be the last attribute when `sometimes` is present, which coincidentally needs to be the `first` attribute. – Ohgodwhy Aug 24 '16 at 21:26
  • @Ohgodwhy but changing it did not help – Dmitry Torba Aug 31 '16 at 20:41

0 Answers0