framework icon indicating copy to clipboard operation
framework copied to clipboard

[Request] nullable validation rule

Open JNK opened this issue 12 years ago • 6 comments

I am running into a problem where I cannot unset a property of a eloquent model, because the validation rule says, that the value must be an integer and must match an existing entry in another table ('alliance_id'=>'integer|exists:alliances,id')

It would be great to have a 'nullable' validation option, which lets the validation pass if alliance_id is set to null (which would override the other rules, similar to the sometimes behavior)

JNK avatar Jul 01 '14 20:07 JNK

If it's null won't all validation be skipped for the attribute? I'm confused.

taylorotwell avatar Jul 02 '14 01:07 taylorotwell

In my case (where I said it should be an integer and it should exist in the other table) the validation failed and said that the field must be an integer.

Am 02.07.2014 um 03:19 schrieb Taylor Otwell [email protected]:

If it's null won't all validation be skipped for the attribute? I'm confused.

— Reply to this email directly or view it on GitHub.

JNK avatar Jul 02 '14 01:07 JNK

Validator won't validate empty variables unless they're required.

Try the following unit test:

$validator =  Validator::make(
    array('alliance_id' => null),
    array('alliance_id' => 'integer|exists:alliances,id')
);

$this->assertFalse($validator->fails());

Maybe you're setting the variable to something while sanitizing the input?

bworwa avatar Jul 04 '14 15:07 bworwa

This appears to no longer be functioning as expected in Laravel 5.3:

$validator =  Validator::make(
    array('alliance_id' => null),
    array('alliance_id' => 'integer')
);

$validator->fails()

Outputs true in php artisan tinker.

Is this something misconfigured with the Validator in my application or expected behavior? If it's expected, is there a way to allow null values as described in this issue?

cabloo avatar Feb 22 '17 06:02 cabloo

check the official docs here

devcircus avatar Feb 22 '17 07:02 devcircus

Thanks @devcircus adding nullable fixed this, even on 5.3.

cabloo avatar Feb 22 '17 17:02 cabloo