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?

Abbas
5,59324 silver badges40 bronze badges
asked May 27, 2015 at 7:45
\$\endgroup\$
2
  • 1
    \$\begingroup\$ Context may help with reviewing this snippets. Could you post the context (the entire validation function)? \$\endgroup\$ Commented May 27, 2015 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\$ Commented May 27, 2015 at 8:18

1 Answer 1

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
}
answered May 27, 2015 at 8:49
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.