vlucas / valitron

Valitron is a simple, elegant, stand-alone validation library with NO dependencies
BSD 3-Clause "New" or "Revised" License
1.57k stars 250 forks source link

Inconsistent validation of null values in and outside of arrays when using optional rule #209

Open ducsuus opened 7 years ago

ducsuus commented 7 years ago

When a field in the data set has the optional rule and a value of null it should still be validated, as it is set. However, if the field is not in an array (is in the first dimension of the data set) and the field is null some (perhaps all) validation rules (for example "lengthMax") will not be evaluated.

This is inconsistent when the field is within an array. If the field is within a second (or greater) dimension of the data set and is null it will be evaluated by these validation rules.

An example can be found here.

Wintereise commented 7 years ago

Just ran into this.

[
            'required' => [
                ['first_name'], ['last_name'], ['email'], ['password']
            ],
            'email' => 'email',
            'optional' => [
                ['phone'], ['timezone'], ['language']
            ],
            'lengthBetween' => [
                ['password', 5, 72]
            ],
            'slug' => [
                ['phone'], ['timezone'], ['language']
            ],
];

This allows the NULL value through on all 3 optional parameters if specified. It's validated if the value is anything else, but NULL is allowed through, always.

willemwollebrants commented 7 years ago

@Wintereise this isn't because of the optional rule:

$v = new Validator(['email' => null]);
$v->rule('email', 'email');
$va->validate(); //returns true

The issue is that Valitron only validates whatever is in the data set, and perceives null as "not there". (In fact, it perceives a lot of stuff as not set, 'email'=>'' will have the same problem)

What happens in my little example is that as far as the validator is concerned, 'email' is not set. Since 'email' is not a required field, the validator just returns true. This is not ideal and it's something I most certainly want to fix in the near future, but it will be a breaking change probably.

What @ducsuus pointed out is that this behavior is different when dealing with a multi-dimensional dataset.