Greetings developers! 🌟 Today, we embark on a journey to master the art of disabling dates in Flatpickr, the date picker library that brings both elegance and functionality to your projects.
Whether you need to restrict specific dates, block out ranges, or dynamically disable dates using a function, Flatpickr has the flexibility you crave.
Let's dive in and harness the full potential of date control with Flatpickr! 📅✨
So, let's see how to disable dates in flatpickr example, disable date in date picker, specific date disable in flatpickr, past date disable in flatpickr, and date range disable in flatpickr.
Step 1: Setting Up Flatpickr
First things first, make sure Flatpickr is included in your project. You can either download it or use the CDN. For simplicity, let's go with 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
Create an HTML input element to serve as your date picker. Give it a unique ID, such as "myDatePicker."
<!-- Your HTML input element -->
<input type="text" id="myDatePicker" placeholder="Select a date">
Step 3: Disable Specific Dates
Let's start by disabling specific dates. In this example, we'll block out January 15, 2024.
// Initialize Flatpickr and disable specific date
const myDatePicker = flatpickr("#myDatePicker", {
disable: ["2024-01-15"],
});
// Initialize Flatpickr and disable specific date
const myDatePicker = flatpickr("#myDatePicker", {
disable: ["2025-01-30", "2025-02-21", "2025-03-08", new Date(2025, 4, 9) ],
dateFormat: "Y-m-d",
});
Step 4: Disable a Date Range
Now, let's disable a date range, say from January 1, 2024, to January 10, 2024.
// Initialize Flatpickr and disable date range
const myDatePicker = flatpickr("#myDatePicker", {
disable: [
{ from: "2024-01-01", to: "2024-01-10" }
],
});
// Initialize Flatpickr and disable date range
const myDatePicker = flatpickr("#myDatePicker", {
dateFormat: "Y-m-d",
disable: [
{
from: "2025-04-01",
to: "2025-05-01"
},
{
from: "2025-09-01",
to: "2025-12-01"
}
],
});
Step 5: Disable Dates Using a Function
For more dynamic control, let's use a function to disable weekends. This example demonstrates how to disable Saturdays and Sundays.
// Initialize Flatpickr and disable dates using a function
const myDatePicker = flatpickr("#myDatePicker", {
disable: [
function(date) {
// Disable weekends (Saturdays and Sundays)
return (date.getDay() === 0 || date.getDay() === 6);
}
],
});
And there you have it! You've successfully wielded the power of Flatpickr to disable specific dates, date ranges, and even utilized a function for dynamic date control.
Top comments (0)