I need to only allow:
- a year
- a year and a month
- a year and a month and a day
I should not allow:
- anything without a year
- a month by itself
- a day by itself
- a month and day
- a year and a day
I have written
if ($year && (($month && $day) || ($month && ! $day) || (! $month && ! $day)))
But it seems rather lengthy – is there a more concise way?
2
Answers
Unit testing helps with clearing up any uncertainly.
My interpretation of your input data is that your non-null values can never be zero. The condition statement below will be making truthy/falsey checks — this means that any encountered
0
values will be evaluated as falsey.Code: (Demo)
$year
value is required.$month
also exists, then it’s still good.$month
does not exists, then$day
must not as well.In other words, the
!$day
check is only executed if$month
is not truthy.You can use a KV diagram to find the expressions, which can be combined with
||
and simplify them. The KV diagram looks like this:Which results in two sub expressions
$year && $month
and$year && !$day
like this:And this can be simplified to: