Framework: Sometimes Validation rule not working

Created on 16 Mar 2017  路  3Comments  路  Source: laravel/framework

  • Laravel Version: 5.4.13
  • PHP Version: 7

Description:

I have a simple form with three fields: "name" that is required, "website" that is optional and is a URL, and finaly "email" that is also optional and is an email.

In my rules method of my FormRequest I defined my rules according to Laravel documentation like that:
return [ 'name' => 'required', 'website' => 'sometimes|url', 'email' => 'sometimes|email' ];

But whatever I try the result is always the same, i got errors telling me that my url and my email are invalid, when i submit my form without them.

Note: I think that it is more suitable to test the rules only if the input value is not null and not an empty string. Cause for example in my case, url and email rules are playing also the same role as the required rule, while if I need them to be mandatory I'd use the required rule with them

Most helpful comment

From the Laravel docs

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

Since 'email' and 'website' are part of the form, they are "present in the input array", unless you're doing something to remove them. They may be empty or null, but the key is still present. Therefore, they will be treated as required.

You should be able to get the results you want using 'url|nullable' and 'email|nullable'.

All 3 comments

Are you using the ConvertEmptyStringsToNull middleware?

From the Laravel docs

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

Since 'email' and 'website' are part of the form, they are "present in the input array", unless you're doing something to remove them. They may be empty or null, but the key is still present. Therefore, they will be treated as required.

You should be able to get the results you want using 'url|nullable' and 'email|nullable'.

Thank you @ntzm and @devcircus

The @devcircus solution worked for me.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

kerbylav picture kerbylav  路  3Comments

YannPl picture YannPl  路  3Comments

Fuzzyma picture Fuzzyma  路  3Comments

felixsanz picture felixsanz  路  3Comments

lzp819739483 picture lzp819739483  路  3Comments