I want to validate the date format on an input using the format mm/dd/yyyy
.
I found below codes in one site and then used it but it doesn't work:
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!');
}
}
Any suggestion about what could be wrong?
Similar to Elian Ebbing answer, but support "\", "/", ".", "-", " " delimiters
The function will return true if the given string is in the right format('MM/DD/YYYY') else it will return false. (I found this code online & modified it a little)
Here is one snippet to check for valid date:
I pulled most of this code from another post found here. I have modified it for my purposes. This works well for what I need. It may help with your situation.
I would use Moment.js for date validation.
Jsfiddle: http://jsfiddle.net/q8y9nbu5/
It's ok if you want to check validate dd/MM/yyyy