check valid date in javascript code example
Example 1: javascript validate date
var date_regex = /^(0[1-9]|1[0-2])\/(0[1-9]|1\d|2\d|3[01])\/(19|20)\d{2}$/;
if (!(date_regex.test(testDate))) {
return false;
}
Example 2: how to validate from and to date using date.parse in javascript
var stringval = '01/03/2012';
var testdate;
try {
testdate = $.datepicker.parseDate('mm/dd/yy', stringval);
// Notice 'yy' indicates a 4-digit year value
} catch (e)
{
alert(stringval + ' is not valid. Format must be MM/DD/YYYY ' +
'and the date value must be valid for the calendar.';
}
Example 3: javascript validate date
function isDate(ExpiryDate) {
var objDate, // date object initialized from the ExpiryDate string
mSeconds, // ExpiryDate in milliseconds
day, // day
month, // month
year; // year
// date length should be 10 characters (no more no less)
if (ExpiryDate.length !== 10) {
return false;
}
// third and sixth character should be '/'
if (ExpiryDate.substring(2, 3) !== '/' || ExpiryDate.substring(5, 6) !== '/') {
return false;
}
// extract month, day and year from the ExpiryDate (expected format is mm/dd/yyyy)
// subtraction will cast variables to integer implicitly (needed
// for !== comparing)
month = ExpiryDate.substring(0, 2) - 1; // because months in JS start from 0
day = ExpiryDate.substring(3, 5) - 0;
year = ExpiryDate.substring(6, 10) - 0;
// test year range
if (year < 1000 || year > 3000) {
return false;
}
// convert ExpiryDate to milliseconds
mSeconds = (new Date(year, month, day)).getTime();
// initialize Date() object from calculated milliseconds
objDate = new Date();
objDate.setTime(mSeconds);
// compare input date and parts from Date() object
// if difference exists then date isn't valid
if (objDate.getFullYear() !== year ||
objDate.getMonth() !== month ||
objDate.getDate() !== day) {
return false;
}
// otherwise return true
return true;
}
function checkDate(){
// define date string to test
var ExpiryDate = document.getElementById(' ExpiryDate').value;
// check date and print message
if (isDate(ExpiryDate)) {
alert('OK');
}
else {
alert('Invalid date format!');
}
}
Example 4: check date clash js
var date1 = [moment("2016-12-06 11:00"), moment("2016-12-06 12:00")];
var date2 = [moment("2016-12-06 10:00"), moment("2016-12-06 13:00")];
var range = moment.range(date1);
var range2 = moment.range(date2);
// has overlapping
if(range.overlaps(range2)) {
if((range2.contains(range, true) || range.contains(range2, true)) && !date1[0].isSame(date2[0]))
alert("time range 1 is completely conflict with time range 2 and vice versa");
else
alert("time range 1 is partially conflict with time range 2 and vice versa");
}