I have the following input for allowing users to select a date in an order form:
<input id="datefield" name="date" type='date' required onkeydown="return false" min='2019-05-10'></input>
I've followed that Tiffany Brown tutorial and I've got it working so an error comes up by doing:
var date = document.querySelector('[type=date]');
function noOrder(e){
var weekDay = new Date( e.target.value ).getUTCDay();
// Days in JS range from 0-6 where 0 is Sunday and 6 is Saturday
if( weekDay == 0){
e.target.setCustomValidity('Unfortunately we cannot deliver cakes on Sundays, please select another day');
} else {
e.target.setCustomValidity('');
}
}
date.addEventListener('input',noOrder);
but when I try to add to it so that the 25th December is unavailable it just stops working completely and no errors appear.
This is what I am doing:
var date = document.querySelector('[type=date]');
function noOrder(e){
var weekDay = new Date( e.target.value ).getUTCDay();
var month = weekDay(e.target.value).getUTCMonth()+1;
var day = weekDay(e.target.value).getUTCDate();
// Days in JS range from 0-6 where 0 is Sunday and 6 is Saturday
if( weekDay == 0){
e.target.setCustomValidity('Unfortunately we cannot deliver cakes on Sundays, please select another day');
}else if (day == 25 && month == 12) {
e.target.setCustomValidity('Unfortunately we cannot deliver cakes on this day, please select another day');
} else {
e.target.setCustomValidity('');
}
}
date.addEventListener('input',noOrder);
What really confuses me is just by adding another variable, eg var month = weekDay(e.target.value).getUTCMonth()+1; the whole thing stops working
Is anyone able to help me with where I am going wrong?
Have gone about it a different way and have it working, I am now doing:
const validate = dateString => {
const day = (new Date(dateString)).getDay();
const month = (new Date(dateString)).getMonth()+1;
const number = (new Date(dateString)).getDate();
if (number == 25 && month == 12) {
return false;
}
return true;
}
// Sets the value to '' in case of an invalid date
document.querySelector('input').onchange = evt => {
if (!validate(evt.target.value)) {
evt.target.value = '';
alert("We cannot deliver cakes on this day. Please select another");
}
}