Help. Date validation with JavaScript
function validateDate(date){ if(date.match(/^\d{4}-\d{2}-\d{2}$/)){ var dateTime; if(!isNaN((dateTime = Date.parse(date + ' 00:00:00')))){ var now = new Date(); now.setHours(0); now.setMinutes(0); now.setSeconds(0); now.setMilliseconds(0); now = now.getTime(); var minDiff = 1000 * 60 * 60 * 24 * 2; var diff = dateTime - now; if(diff >= minDiff){ return true; } else { alert('Entered date has to be 2 days ahead current date.'); } } else { alert('Wrong value.'); } } else { alert('Wrong format.'); } return false; }
What I did is parse date from the input to check if it is valid, because 2016-99-99 will match patter but won't be valid date, parse returns NaN in such case.
Notice that I added time string, I noticed that without it my date end up ahead of value of timezone, so my timezine is GMT +2 and when i entered 2016-10-30 I ended up with timestamp for datetime of 2016-10-30 02:00:00
So when date is valid, parse returns timestamp with milliseconds, then I create new Date object that defaults to current datetime, I reset hours, minutes, seconds and milliseconds to compare just dates, then I convert Date object to timestamp by calling getTime method and finally I calculate difference between entered and current date and compare it with the minimal difference.
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now