Argolian's avatar

Validation only if field is NOT null

I've been trying to work out how to do the following:

I have three fields which must be different from each other only if they contain a value. If they are empty or null then I don't want it checking.

I guess what I'm looking for is something like

differentIfNotNull:field2|differentIfNotNull:field3

or

differentIfNotNull:[field2,field3...etc]

Is there a way to do this? I already tried

"field1" => "nullable|different:field2|different:field3"

But if all fields are null or empty it throws a validation error complaining they are not different, which of course they aren't but I want to validation to be skipped if the field is empty.

0 likes
6 replies
CorvS's avatar

@argolian If I understand you correctly simply add sometimes to your validation. It's part of what @sr57 suggested.

'field1' => 'sometimes|nullable|different:field2|different:field3',
...
sr57's avatar

Hi @corvs

sometimes is used to test if field exists not if it is null.

Argolian's avatar

Thanks @sr57

I've already tried the solution you suggested but it doesn't work.

'field1'=>'exclude_if:field2,null|different:field2'

Still tells me that field1 and field2 cannot both be null. Is it not possible to use null like this?

sr57's avatar

In this example, you should exclude_if field1 ... see my example

sr57's avatar

-1- both solutions should work : nullable or exclude_if:...,null

-2- I should write your code like this :

			'f1' => 'nullable',
			'f2' => 'nullable|different:f1',
#	or		'f2' => 'exclude_if:f2,null|different:f1',
			'f3' => 'nullable|different:f1|different:f2',

Please or to participate in this conversation.