2

I would like to block my user from selecting a date that happened in the past in a lightning-input of type date. For this I would like to use the min attribute of the type date.

This is the html code for the lightning-input :

<lightning-input name="fromDate" label='From Date' type="date" min={todaysDate} onchange=dateEventHandler}
                 value={fromDate} date-style="short" required>
</lightning-input>

And here is the js code to get the date

   get todaysDate() {
       var today = new Date();
       return today.toISOString();
   }

Unfortunately, it doesn't work when I select the current date :

enter image description here

Any Idea how to solve it ?

2
  • Once you select your current date, click outside this input, it should go away – salesforce Developer Sep 16 '20 at 10:32
  • 2
    No this is what happens after I click away. – Sacha Dieryck Sep 16 '20 at 10:35
2

Date() actually returns the current date time, you can see that the issue is with the time when you preview your component in the playground.

LWC playground error

Assuming you want to just restrict by the current day you need replace your todaysDate() method with something like this:

get todaysDate() {
        var today = new Date();
        var dd = String(today.getDate()).padStart(2, '0');
        var mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0!
        var yyyy = today.getFullYear();
        today = mm + '/' + dd + '/' + yyyy;
        return today
    }

as per https://stackoverflow.com/a/4929629/9623950

Which results in the input accepting today's date. I've left the formatting the same as in the linked example, but you can change it to whatever you require.

enter image description here

2
  • +1 I think the format changes according to the locality of users. – rahul gawale Sep 16 '20 at 11:47
  • 2
    @rahulgawale strangely enough the locale changes the error message but so does the format that I return. If I return today = mm + '/' + dd + '/' + yyyy; The error message will be 'Value must be 09/16/2020 or later'. for every locale. If I return today = yyyy + '/' + mm + '/' + dd; The error message is 'Value must be 16.09.2020 or later'. (for german locale). 'Value must be 16 Sep 2020 or later'. (for french and english locale). – Sacha Dieryck Sep 16 '20 at 15:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.