How to Disable Weekend Saturday and Sunday in Flatpickr

A datepicker is a useful component in web development for selecting dates. Sometimes, you may need to restrict the use of Saturdays and Sundays in your datepicker, especially if your application operates only on weekdays. Fortunately, with popular JavaScript libraries like Flatpickr, you can easily disable Saturdays and Sundays. In this article, we’ll walk you through the steps to achieve this.

Step 1: Install Flatpickr

The first step is to ensure you have installed the Flatpickr library in your web project. You can download Flatpickr from its official website or use package managers like npm or Yarn.

Step 2: Create Date Input

Next, you need to create a date input in HTML. This is the element where users will select a date.

<input type="text" class="basic-datepicker">

Step 3: Configure Flatpickr

You can configure Flatpickr to disable Saturdays and Sundays using the disable option in the configuration. Here's an example of how to do it:

$(".basic-datepicker").flatpickr({
    "disable": [
        function(date) {
            // return true to disable
            return (date.getDay() === 0 || date.getDay() === 6);
        }
    ],
    "locale": {
        "firstDayOfWeek": 1 // start week on Monday
    }
});

In the example above, we use a function that returns true for dates that fall on a Saturday (date.getDay() === 6) or Sunday (date.getDay() === 0). This will automatically disable those days in the datepicker.

enter image description here

Step 4: Add Additional Options (Optional)

You can also add additional options to the datepicker as per your requirements, such as date format, theme, or minimum and maximum date limits.

const datepicker = flatpickr("#datepicker", {
  disable: [
    function(date) {
      return (date.getDay() === 6 || date.getDay() === 0);
    }
  ],
  dateFormat: "d-m-Y",   // Date format (e.g., "31-12-2023")
  minDate: "today",      // Minimum date limit is today
  maxDate: "2024-12-31"  // Maximum date limit is December 31, 2024
});

Conclusion

By following the steps above, you can easily disable Saturdays and Sundays in a datepicker or Flatpickr. This is useful if you want to limit date selection to weekdays in your web application. We hope this article helps you implement this feature in your project. Happy coding!

Share: