mymth / vanillajs-datepicker

A vanilla JavaScript remake of bootstrap-datepicker for Bulma and other CSS frameworks
MIT License
743 stars 153 forks source link

Add custom validation in DateRangePicker #191

Open weinnandhasanion opened 1 month ago

weinnandhasanion commented 1 month ago

So basically, I want to have a custom format validator (using dayjs) applied to the DateRangePicker where I want to clear the value if an invalid date format is entered. This is doable for the DatePicker since I can easily override the instance's update() method, but how can I do this for the DateRangePicker? Below is a scenario

Valid formats: ['DD MMM YYYY', 'DD/MM/YYYY', 'DD-MM-YYYY'] // 09 Aug 2024, 09/08/2024, 09-08-2024 Display format: 'DD MMM YYYY' (set via format option)

If input is of invalid format:
 Clear field
Else:
 Register value in DD MMM YYYY format

I tried overriding setDates() but it seems like the method isn't being invoked on change, or am I missing something? Please help. Thanks

mymth commented 1 month ago

setDates() has no role in user interaction. It's just like a utility function to programmatically change both dates at once.

Handling user action on a child date picker is fully done by the date picker itself, then after a change is made, the date range picker normalizes the date range (filling/clearing the other side if one side is empty, flipping the dates if end < start) with the changeDate event listener it added to the child input elements. This is why you don't see setDates() being invoked on change.

Although overriding Datepicker's method through DateRangePicker is not possible, you can do something similar like this: https://codepen.io/mymth/pen/WNqZpGM