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?
-
1\$\begingroup\$ Context may help with reviewing this snippets. Could you post the context (the entire validation function)? \$\endgroup\$Mast– Mast ♦2015年05月27日 08:10:38 +00:00Commented 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\$Lars Ebert-Harlaar– Lars Ebert-Harlaar2015年05月27日 08:18:03 +00:00Commented May 27, 2015 at 8:18
1 Answer 1
You have two situations where input is invalid:
- fieldD is empty and one or more are empty
- 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
}