How to Limit the Years Inside Your Date Picker

Overview

Would you like to limit the years that show inside your Date Picker form field? You may want to restrict your form to only select birthdays that are 18 years or older. Inside this tutorial, we’ll walk you through the JavaScript needed to restrict this year’s range.

Setup

Your first step is to add a Date field to your form. Once inside the Form Builder, select the Date / Time form field from your available Fields. Next, open Field Options and click the Advanced Options to select the Date Picker for the Date Type.

Add the date picker form field to your form

Once you’ve added your Date field, you’ll need to copy the following code snippet to your site.

/**
 * Limit the dates available in the Date Time date picker to anything within last 18 years.
 *
 */
function wpf_dev_limit_date_picker_years() {
        ?>
        <script type="text/javascript">
                var d = new Date();
                window.wpforms_datepicker = {
                        disableMobile: true,
                        // Don't allow users to pick dates less than 18 years ago
                        maxDate: d.setDate( d.getDate() - 6574 ),
                }
        </script>
        <?php
}
add_action( 'wpforms_wp_footer_end', 'wpf_dev_limit_date_picker_years' );

Years are now limited to anything in the last 18 years

And that’s it! You’ve now limited the years available inside your date picker. Would you like also allow for a date range in your date picker? Check out our tutorial on How to Allow Date Range or Multiple Dates in Date Picker.

Action Reference: wpforms_wp_footer_end

FAQ

Q: Can I also apply this to the Date Dropdown?

A: Absolutely, but the Date Dropdown can only be used with manual date ranges. Following this tutorial, just follow this tutorial to change the year range $args['years'] = range( 2019, 2020 ); to enter the range of years you want to limit.