Reputation: 160
I have this function which consists in validating a date entered by the user. So far I only check that the date format is correct (dd/mm/yyyy).
But, I also wanted to check that the date entered is today's date, not a prior or future date.
I thought of something like var currentdate = new Date();
and then compare both, but I have not tinkered with dates yet and didn't want to mess it up. Any ideas how I should write it?.
function validate(){
var date = $("#dateentry").val();
if (/^(0[1-9]|1\d|2\d|3[01])\/(0[1-9]|1[0-2])\/(19|20)\d{2}$/.test(date)){
$("#msg").html("The date format is correct");
}else{
$("#msg").html("The date format must be dd/mm/yyyy");
}
}
Upvotes: 0
Views: 110
Reputation: 147363
You should always manually parse date strings, especially if they aren't the format included in ECMA-262 (ISO 8601 extended format).
A function to parse and validate a date in d/m/y format is below. You can then check if it's today or not by creating a date for today, setting the time to 00:00:00 and comparing:
function parseDMY(s) {
var b = (''||s).match(/\d+/g);
var d = new Date(b[2]||0, (b[1]||0)-1, b[0]);
return d && d.getMonth() == b[1]-1? d : new Date(NaN);
}
var today = new Date();
today.setHours(0,0,0,0);
console.log('Today is: ' + today);
// Returns true on 15 June 2016
var s = '15/06/2016';
console.log('Is today ' + s + '? ' + (parseDMY(s).getTime() == today.getTime()))
This also removes the need test the values entered separately.
Upvotes: 2
Reputation: 50291
If you are using input type="date"
you can disable the previous dates, thus avoiding any validation
Hope this snippet will be useful
HTML
<input type="date" name="dateTime" id="dateTime">
JS
var dateTime = document.getElementById("dateTime").value;
var today = new Date().toISOString().split('T')[0];
document.getElementById("dateTime").setAttribute('min', today);
Upvotes: 1
Reputation: 169
I think your only choice is comparison with the date today.
var todaysDate = new Date();
if(new Date(date).setHours(0,0,0,0) >= todaysDate.setHours(0,0,0,0));
{
$("#msg").html("Date should not be prior or greater that current date");
}
Upvotes: 2