Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make flatpickr input required

I'm using the amazing flatpickr on a project and need the calendar date to be mandatory.

I'm trying to have all the validation in native HTML, so I was naively trying with just adding the required attribute to the input tag, but that doesn't appear to be working.

Is there a way of natively making a date mandatory with flatpickr or do I need to write some custom checks?

like image 484
stassinari Avatar asked Jul 19 '17 11:07

stassinari


People also ask

How do I change the default date on Flatpickr?

If you want to preload a date, you only need to pass one parameter in - defaultDate. This can be set to any date you'd like, but for instructional purposes, we set it to a value of "today", which returns the user's current date.

How do I turn off the date on my Flatpickr?

Disabling dates by a function:#The function takes in a Date object, and should return a boolean value. If the function returns true , the date will be disabled. This flexibility allows us to use any arbitrary logic to disable dates.

What is a Flatpickr?

flatpickr is a lightweight and powerful datetime picker. Lean, UX-driven, and extensible, yet it doesn't depend on any libraries. There's minimal UI but many themes. Rich, exposed APIs and event system make it suitable for any environment.


2 Answers

You can easily achieve this by:

Passing allowInput:true in flatpickr config.

As example:

flatpickrConfig = {
    allowInput: true, // prevent "readonly" prop
};

From the documentation:

Allows the user to enter a date directly into the input field. By default, direct entry is disabled.

The downside of this solution is that you should enable the direct entry (but ideally form validation should occur whether or not direct entry is enabled).

But if you don't want to enable the direct entry to solve this problem, you can use the code below as a workaround:

flatpickrConfig = {
    allowInput:true,
    onOpen: function(selectedDates, dateStr, instance) {
        $(instance.altInput).prop('readonly', true);
    },
    onClose: function(selectedDates, dateStr, instance) {
        $(instance.altInput).prop('readonly', false);
        $(instance.altInput).blur();
    }
};

This code remove the readonly property when it is not in focus so that html validation can occur and add back the readonly prop when it is in focus to prevent manual input. More details about it here.

like image 105
Claudio Augusto Pereira Rolim Avatar answered Sep 30 '22 01:09

Claudio Augusto Pereira Rolim


After digging a bit into the GitHub repo, I found a closed issue that points out that the issue will not be addressed.

In the same Issue page there is a workaround that seems to do the trick:

$('.flatpickr-input:visible').on('focus', function () {
    $(this).blur()
})
$('.flatpickr-input:visible').prop('readonly', false)
like image 36
stassinari Avatar answered Sep 30 '22 00:09

stassinari