skip to Main Content

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


  1. 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)

    if ($year && ($month || !$day)) {
    
    • The $year value is required.
    • If the $month also exists, then it’s still good.
    • If the $month does not exists, then $day must not as well.
      In other words, the !$day check is only executed if $month is not truthy.
    Login or Signup to reply.
  2. You can use a KV diagram to find the expressions, which can be combined with || and simplify them. The KV diagram looks like this:

       |  Y | !Y |
    ---+----+----+---
       |  1 |  0 |  D
     M +----+----+---
       |  1 |  0 | 
    ---+----+----+ !D
       |  1 |  0 | 
    !M +----+----+---
       |  0 |  0 |  D
    ---+----+----+---
    

    Which results in two sub expressions $year && $month and $year && !$day like this:

    ($year && $month) || ($year && !&day)
    

    And this can be simplified to:

    $year && ($month || !$day)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search