We needed to add a date field to a form made using Gravity Forms to allow visitors to select a birth date and not allow users under or over a certain age to submit the form.

Our first thought was to simple use the excellent conditional options inside Gravity Forms to disable the submit button if the entered age was outside the range we wanted to allow – however, Gravity Forms does not allow conditional actions based on date fields – so we looked deeper.

We had previously used a filter hooked to gform_validation_{$form_id}  to add a validation error based on a calculation of the submitted date – but this solution is both complex and very form, field and date format specific – and can be a pain to test on development and staging versions which usually have some disparity between form and field ids.

So, we started to think about a more generic solution which could be controlled by the content editors from inside the Gravity Forms form editor.

The Date field uses the jQuery datepicker plugin to build the input on the front-end – and this can be hooked into using gform_post_render – allowing us to re-instantiate the datepicker with custom configurations, which also bind to forms reloaded after AJAX submissions.

Gravity Forms allows us to add additional CSS classes to the <li> that wraps around each field using the “Appearance” tab in the form editor:

gravity_forms_date_limiter

So we entered the following in the CSS box – setting the min and max date range, limiting the dates shown to between 13 and 18 years from the current date:

limit_date min_date_-18y max_date_-13y

Then we added the following chunk of jQuery to the theme’s JavaScript file, hooking into the Gravity Forms action gform_post_render:

Enjoy and please feel free to comment and suggest improvements.