'flatpickr - issue while entering dates manually

Using flatpickr 4.6.11, I have the following code:

  date_from = flatpickr("#myDatePickerFrom", {
        locale: 'es',               
        altInput: true,
        altFormat: "F j, Y",
        dateFormat: "m/d/Y H:i:S",
        allowInput: true,
        onOpen: function (selectedDates, dateStr, instance) {
            instance.setDate(instance.input.value, false);
        }
    });

I can select a date using the calendar and it is displayed in the correct format (Marzo 22, 2022) but when I try to enter a date manually, I keep getting "Invalid date provided".I tried 01/25/2002, 25/01/2022, 2022/01/25, 2022-01-25 and many other and keep getting the same error. What I am doing wrong? Do I need to specify the format of the input anywhere?

Thank you, Sylvain



Solution 1:[1]

The issue is in the part that you display your date format as altFormat: "F j, Y", output: Marzo 22, 2022.

If you enter Marzo 22, 2022 it will accept your input. Another way is to change the input format to altFormat: "m/d/Y H:i:S", this way it will accept manual inputs like 01/01/2022.

Additionally you can also have a look at the parseDate function (parseDate expects a date string and must return a Date object)

See an example of parseDate function here:

$(document).ready(function() {
  const date_from = $('#myDatePickerFrom').flatpickr({
    //locale: 'es',               
    altInput: true,
    //altFormat: "m/d/Y H:i:S",
    //dateFormat: "m/d/Y H:i:S",
    allowInput: true,
    parseDate: (datestr, format) => {
      return new Date(datestr.replace(/(\d{2})-(\d{2})-(\d{4})/, "$2/$1/$3"));
    },
    onOpen: function(selectedDates, dateStr, instance) {
      instance.setDate(instance.input.value, false);
    }
  });
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/flatpickr/4.6.11/flatpickr.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/flatpickr/4.6.11/flatpickr.min.js"></script>
<input id="myDatePickerFrom" style="width:200px;">

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Crezzur