Answers.Body: <p><a href="https://lexi-lambda.github.io/blog/2019/11/05/parse-don-t-validate/" rel="nofollow noreferrer">Parse, don't validate.</a> Instead of validating the format, which will get complicated fast, parse it as a date and see if it works or not.</p>
  <p>The simplest solution is something like this:</p>
  <pre class="lang-twig prettyprint-override"><code>{% set dateParam = craft.app.request.getQueryParam('after') %}
  {% if afterParam is not empty %}
    {% set entriesQuery = entriesQuery.after(afterParam | date) %}
  {% endif %}
  </code></pre>
  <p>This will throw an exception if the <code>afterParam</code> is not in any valid date format. In the production environment, this will result in a simple error page, which you can customize with a <a href="https://craftcms.com/docs/3.x/routing.html#error-templates" rel="nofollow noreferrer">custom error template</a>.</p>
  <p>Now you may say that this is an unacceptable user experience, but it depends on what kind of interface you're presenting in the user face. What kind of input are you providing for the date parameter? If you use a native <code>date</code> input, the browser will display a date picker and will prevent users from entering an invalid date. You can also use JavaScript to catch invalid formats and prevent them from being sent to the server. So a regular user will never encounter the exception view, since the UX for validating date inputs is handled on the client-side – by the browser itself if you're using native date inputs. In this case, the server-side date parsing is about security, not user experience, so an exception is fine.</p>
  <p>If you still want to handle invalid date formats gracefully, you can create a simple <a href="https://twig.symfony.com/doc/2.x/advanced.html#tests" rel="nofollow noreferrer">Twig test</a> in a <a href="https://craftcms.com/docs/3.x/extend/extending-twig.html#register-a-twig-extension" rel="nofollow noreferrer">Twig extension</a> that will try to parse the parameter as a date and returns true or false based on whether it succeeds:</p>
  <pre class="lang-php prettyprint-override"><code>public function getTests()
  {
      return [
          new \Twig\TwigTest('valid_date', function($date) {
              try {
                  $dateObj = new \DateTime($date);
                  return true;
              } catch (\Exception $e) {
                  return false;
              }
          }),
      ];
  }
  </code></pre>
  <p>Now you can use it like this to check if the date param is valid:</p>
  <pre class="lang-twig prettyprint-override"><code>{% set is_valid_date = dataParam is valid_date %}
  </code></pre>
  <p>You could also make this a function that either returns the <code>DateTime</code> object if the format is valid or <code>null</code> if it isn't. Then you can check the return value and only apply it to the query if it isn't <code>null</code>, and display and error message if it is.</p>
  
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2022-02-14T10:25:24.083Z
Answers.LastActivityDate: 2022-02-14T10:25:24.083Z
Answers.UserDisplayName: MoritzLost
Body: <p>I have a form that lets you search articles by date.<br />
  The 'Results' template uses dates from the query string in an Entries Query like this:</p>
  <pre><code>{% set afterParam = craft.app.request.getQueryParam('after') %}
  {% if afterParam is not empty %}
    {% set entriesQuery = entriesQuery.after(afterParam) %}
  {% endif %}
  </code></pre>
  <p>I'd like to avoid errors when a date is invalid... but I can't find a simple, bullet-proof way to validate.<br />
  I can use a regex to check each date parameter looks like YYYY-MM-DD:</p>
  <pre><code>{% if dateParam matches '/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/' %}
  ...
  </code></pre>
  <p>But this doesn't stop strings like '2022-13-01' getting through (here, the invalid Month causes a Database Exception).<br />
  Does anyone know a straight-forward way to validate date strings in Twig?</p>
  
Tags: <templating><datetime><validation>
Title: Checking for a valid date in a query string parameter using Twig
ThreadText: # Checking for a valid date in a query string parameter using Twig
  
  (Asked by: username_0 on 2022-02-13)
  
  I have a form that lets you search articles by date.  
  The 'Results' template uses dates from the query string in an Entries Query like this:
  
  ```
  {% set afterParam = craft.app.request.getQueryParam('after') %}
  {% if afterParam is not empty %}
    {% set entriesQuery = entriesQuery.after(afterParam) %}
  {% endif %}
  
  ```
  
  I'd like to avoid errors when a date is invalid... but I can't find a simple, bullet-proof way to validate.  
  I can use a regex to check each date parameter looks like YYYY-MM-DD:
  
  ```
  {% if dateParam matches '/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/' %}
  ...
  
  ```
  
  But this doesn't stop strings like '2022-13-01' getting through (here, the invalid Month causes a Database Exception).  
  Does anyone know a straight-forward way to validate date strings in Twig?
  
  **Tags:** templating, datetime, validation
  
  
  ---
  
  ## 1 answers
  
  ### Answer by username_1 on 2022-02-14. Score: 1 | Accepted answer
  
  [Parse, don't validate.](https://lexi-lambda.github.io/blog/2019/11/05/parse-don-t-validate/) Instead of validating the format, which will get complicated fast, parse it as a date and see if it works or not.
  
  The simplest solution is something like this:
  
  ```twig
  {% set dateParam = craft.app.request.getQueryParam('after') %}
  {% if afterParam is not empty %}
    {% set entriesQuery = entriesQuery.after(afterParam | date) %}
  {% endif %}
  
  ```
  
  This will throw an exception if the `afterParam` is not in any valid date format. In the production environment, this will result in a simple error page, which you can customize with a [custom error template](https://craftcms.com/docs/3.x/routing.html#error-templates).
  
  Now you may say that this is an unacceptable user experience, but it depends on what kind of interface you're presenting in the user face. What kind of input are you providing for the date parameter? If you use a native `date` input, the browser will display a date picker and will prevent users from entering an invalid date. You can also use JavaScript to catch invalid formats and prevent them from being sent to the server. So a regular user will never encounter the exception view, since the UX for validating date inputs is handled on the client-side – by the browser itself if you're using native date inputs. In this case, the server-side date parsing is about security, not user experience, so an exception is fine.
  
  If you still want to handle invalid date formats gracefully, you can create a simple [Twig test](https://twig.symfony.com/doc/2.x/advanced.html#tests) in a [Twig extension](https://craftcms.com/docs/3.x/extend/extending-twig.html#register-a-twig-extension) that will try to parse the parameter as a date and returns true or false based on whether it succeeds:
  
  ```php
  public function getTests()
  {
      return [
          new \Twig\TwigTest('valid_date', function($date) {
              try {
                  $dateObj = new \DateTime($date);
                  return true;
              } catch (\Exception $e) {
                  return false;
              }
          }),
      ];
  }
  
  ```
  
  Now you can use it like this to check if the date param is valid:
  
  ```twig
  {% set is_valid_date = dataParam is valid_date %}
  
  ```
  
  You could also make this a function that either returns the `DateTime` object if the format is valid or `null` if it isn't. Then you can check the return value and only apply it to the query if it isn't `null`, and display and error message if it is.
  
  
  ---
  
  