Reputation: 50291
I am setting the minimum date in html5 date input, but I can still select a date prior to minimum date using date up/down arrow.
For example I have set the min date to 2018-02-22
but once I have selected the month or date using down arrow a date prior to min date is getting selected.
Can I restrict it using any HTML date property
Setting min date and selecting it
Able to select previous date & getting date in the console
document.getElementById('button').addEventListener('click', function() {
var x = document.getElementById('date').value;
console.log(x);
})
<input type="date" min="2018-02-22" id="date">
<button type="button" id="button">Get Date</button>
Upvotes: 3
Views: 6691
Reputation: 206
For this (I can still select a date prior to minimum date using date up/down arrow)to happen you should set max date also, as shown below
<input type="date" min="2018-02-22" id="date" max="2018-02-28">
Upvotes: 2
Reputation: 8481
Seems like the browser only enforces min and max if you try to submit the value.
If you use min and max to restrict the available dates (see Setting maximum and minimum dates), supporting browsers will display an error if you try to submit a date that is outside the set bounds. However, you'll have to check the results to be sure the value is within these dates, since they're only enforced if the date picker is fully supported on the user's device.
But you can easily validate the value using JavaScript:
document.getElementById('button').addEventListener('click', function() {
var x = document.getElementById('date').value;
console.log(x);
});
document.getElementById('date').addEventListener('change', function () {
if (this.value < this.min) this.value = this.min;
});
<input type="date" min="2018-02-22" id="date" required>
<button type="button" id="button">Get Date</button>
Upvotes: 1