2
\$\begingroup\$

I have a group of four inputs, the first three are required, the fourth is optional.

$fieldA
$fieldB
$fieldC
$fieldD #Optional

So to validate the inputs, I just use this:

if($fieldA === '' || $fieldB === '' || $fieldC === '') {
    #error
}

That works pretty well, except there is a special case: If all four inputs are empty, the input is still valid.

That special case complicates the if condition quite a bit:

if(($fieldA !== '' || $fieldB !== '' || $fieldC !== '' || $fieldD !== '')
    && ($fieldA === '' || $fieldB === '' || $fieldC === '')) {
    #error
}

The condition in the first pair of parenthesis makes sure that at least one field is not empty, while the rest of the condition makes sure that none of the required fields is empty.

Is there some sneaky way to simplify that if statement that I did not think of?

\$\endgroup\$
2
  • 1
    \$\begingroup\$ Context may help with reviewing this snippets. Could you post the context (the entire validation function)? \$\endgroup\$
    – Mast
    May 27 '15 at 8:10
  • \$\begingroup\$ Actually, that is the whole validation: I have four inputs and that group of inputs is only valid if all of them are empty or at least the first three are not empty. No further validation is needed in this case. \$\endgroup\$
    – Lars Ebert
    May 27 '15 at 8:18
3
\$\begingroup\$

You have two situations where input is invalid:

  1. fieldD is empty and one or more are empty
  2. fieldD is not empty and one ore more are empty

This makes that you have to check for different situations and so your if-statement cannot really be shortened to one statement.

What you also can do is loop over the fields and do a count of the empty fields and validate this:

$emptyFields = 0;

foreach(array($fieldA, $fieldB, $fieldC, $fieldD)as $field) {
    if ($field === '') {
        $emptyFields++;
    }
}

if ($emptyFields === 4 || $emptyFields === 0 || ($emptyFields === 1 && $fieldD === '')) {
    //input is VALID
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.