WillardSolutions
WillardSolutions

Reputation: 2314

Respect Validation for two fields

I need to validate form data with Respect. At least one of these fields must have a value: $vfname and $vlname. After some trial and error, I found that I can concatenate and test with notEmpty():

v::StringType()->notEmpty()->assert($vfname . $vlname)

But this seems really hacky. Is there a better way to validate so that at least one of these fields has a value?

Upvotes: 1

Views: 1446

Answers (2)

henriquemoody
henriquemoody

Reputation: 76

Validation supports OR operations with the OneOf rule. Besides, if you are validating form data, the Key rule will be handy:

v::oneOf(
    v::key('vfname', v::stringType()->notEmpty()),
    v::key('vlname', v::stringType()->notEmpty())
)
->assert(['vfname' => $vfname, 'vlname' => $vlname]);

Upvotes: 3

Daishi
Daishi

Reputation: 14189

Why not this then ?

v::boolType()->validate(!empty($vfname) || !empty($vlname));

Note : an advantage of using empty() is that it will not raise any Undefined variable notice, if it's a matter for you.

Upvotes: 0

Related Questions