How to set minDate and maxDate in Flatpickr

Hello developers! 🌟 Today, I'm excited to walk you through the ins and outs of setting default dates, minimum dates (minDate), and maximum dates (maxDate) in Flatpickr, the sleek and flexible date picker library.

Whether you're working on a project that demands precise date selections or you simply want to enhance the user experience, Flatpickr has got your back.

So, let's dive into the magic of date handling with Flatpickr! 📅✨

So, let's see how to set the min date and max date in flatpickr, how to set the min date in date picker, how to set the max date in flatpickr, how to set the min date and max date in date picker, how to set the default date in flatpickr.

Step 1: Include Flatpickr in Your Project

First things first, make sure you have Flatpickr integrated into your project. You can either download it or include it via CDN. For this guide, let's use the CDN.

<!-- Include Flatpickr CSS and JS via CDN -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>

 

Step 2: Create an HTML Input Element

 

Next, create an HTML input element to serve as your date picker. Give it a unique ID; for example, "myDatePicker."

<!-- Your HTML input element -->
<input type="text" id="myDatePicker" placeholder="Select a date">

 

Step 3: Initialize Flatpickr with Default Date

Now, let's initialize Flatpickr and set a default date. In this example, I'll use today's date as the default.

// Initialize Flatpickr with defaultDate
const myDatePicker = flatpickr("#myDatePicker", {
    defaultDate: "today",
});

 

Step 4: Add minDate and maxDate Constraints

To set minimum and maximum dates, update the Flatpickr initialization code:

// Initialize Flatpickr with defaultDate, minDate, and maxDate
const myDatePicker = flatpickr("#myDatePicker", {
    defaultDate: "today",
    minDate: "2024-01-01",
    maxDate: "2024-12-31",
});
const myDatePicker = flatpickr("#myDatePicker", {
    minDate: "today",
    maxDate: new Date().fp_incr(14) // 14 days from now
});
const myDatePicker = flatpickr("#myDatePicker", {
    dateFormat: "d.m.Y",
    maxDate: "14.02.2024"
});

And there you have it! You've successfully set up Flatpickr with a default date, minDate, and maxDate.

 


You might also like:

techsolutionstuff

Techsolutionstuff | The Complete Guide

I'm a software engineer and the founder of techsolutionstuff.com. Hailing from India, I craft articles, tutorials, tricks, and tips to aid developers. Explore Laravel, PHP, MySQL, jQuery, Bootstrap, Node.js, Vue.js, and AngularJS in our tech stack.

RECOMMENDED POSTS

FEATURE POSTS