Detecting an "invalid date" Date instance in JavaScript - javascript

I'd like to tell the difference between valid and invalid date objects in JS, but couldn't figure out how:
var d = new Date("foo");
console.log(d.toString()); // shows 'Invalid Date'
console.log(typeof d); // shows 'object'
console.log(d instanceof Date); // shows 'true'
Any ideas for writing an isValidDate function?
Ash recommended Date.parse for parsing date strings, which gives an authoritative way to check if the date string is valid.
What I would prefer, if possible, is have my API accept a Date instance and to be able to check/assert whether it's valid or not. Borgar's solution does that, but I need to test it across browsers. I also wonder whether there's a more elegant way.
Ash made me consider not having my API accept Date instances at all, this would be easiest to validate.
Borgar suggested testing for a Date instance, and then testing for the Date's time value. If the date is invalid, the time value is NaN. I checked with ECMA-262 and this behavior is in the standard, which is exactly what I'm looking for.

Here's how I would do it:
if (Object.prototype.toString.call(d) === "[object Date]") {
// it is a date
if (isNaN(d)) { // d.getTime() or d.valueOf() will also work
// date object is not valid
} else {
// date object is valid
}
} else {
// not a date object
}
Update [2018-05-31]: If you are not concerned with Date objects from other JS contexts (external windows, frames, or iframes), this simpler form may be preferred:
function isValidDate(d) {
return d instanceof Date && !isNaN(d);
}
Update [2021-02-01]: Please note that there is a fundamental difference between "invalid dates" (2013-13-32) and "invalid date objects" (new Date('foo')). This answer does not deal with validating date input, only if a Date instance is valid.

Instead of using new Date() you should use:
var timestamp = Date.parse('foo');
if (isNaN(timestamp) == false) {
var d = new Date(timestamp);
}
Date.parse() returns a timestamp, an integer representing the number of milliseconds since 01/Jan/1970. It will return NaN if it cannot parse the supplied date string.

You can check the validity of a Date object d via
d instanceof Date && isFinite(d)
To avoid cross-frame issues, one could replace the instanceof check with
Object.prototype.toString.call(d) === '[object Date]'
A call to getTime() as in Borgar's answer is unnecessary as isNaN() and isFinite() both implicitly convert to number.

shortest answer to check valid date
if(!isNaN(date.getTime()))

My solution is for simply checking whether you get a valid date object:
Implementation
Date.prototype.isValid = function () {
// An invalid date object returns NaN for getTime() and NaN is the only
// object not strictly equal to itself.
return this.getTime() === this.getTime();
};
Usage
var d = new Date("lol");
console.log(d.isValid()); // false
d = new Date("2012/09/11");
console.log(d.isValid()); // true

I have seen some answers that came real close to this little snippet.
JavaScript way:
function isValidDate(dateObject){
return new Date(dateObject).toString() !== 'Invalid Date';
}
console.log(isValidDate('WTH')); // -> false
console.log(isValidDate(new Date('WTH'))); // -> false
console.log(isValidDate(new Date())); // -> true
ES2015 way:
const isValidDate = dateObject => new Date(dateObject)
.toString() !== 'Invalid Date';
console.log(isValidDate('WTH')); // -> false
console.log(isValidDate(new Date('WTH'))); // -> false
console.log(isValidDate(new Date())); // -> true

You can simply use moment.js
Here is an example:
var m = moment('2015-11-32', 'YYYY-MM-DD');
m.isValid(); // false
The validation section in the documentation is quite clear.
And also, the following parsing flags result in an invalid date:
overflow: An overflow of a date field, such as a 13th month, a 32nd day of the month (or a 29th of February on non-leap years), a 367th day of the year, etc. overflow contains the index of the invalid unit to match #invalidAt (see below); -1 means no overflow.
invalidMonth: An invalid month name, such as moment('Marbruary', 'MMMM');. Contains the invalid month string itself, or else null.
empty: An input string that contains nothing parsable, such as moment('this is nonsense');. Boolean.
Etc.
Source: http://momentjs.com/docs/

Would like to mention that the jQuery UI DatePicker widget has a very good date validator utility method that checks for format and validity (e.g., no 01/33/2013 dates allowed).
Even if you don't want to use the datepicker widget on your page as a UI element, you can always add its .js library to your page and then call the validator method, passing the value you want to validate into it. To make life even easier, it takes a string as input, not a JavaScript Date object.
See: http://api.jqueryui.com/datepicker/
It's not listed as a method, but it is there-- as a utility function. Search the page for "parsedate" and you'll find:
$.datepicker.parseDate( format, value, settings ) - Extract a date from a string value with a specified format.
Example usage:
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.';
}
(More info re specifying date formats is found at http://api.jqueryui.com/datepicker/#utility-parseDate)
In the above example, you wouldn't see the alert message since '01/03/2012' is a calendar-valid date in the specified format. However if you made 'stringval' equal to '13/04/2013', for example, you would get the alert message, since the value '13/04/2013' is not calendar-valid.
If a passed-in string value is successfully parsed, the value of 'testdate' would be a Javascript Date object representing the passed-in string value. If not, it'd be undefined.

After reading every answer so far, I am going to offer the most simple of answers.
Every solution here mentions calling date.getTime(). However, this is not needed, as the default conversion from Date to Number is to use the getTime() value. Yep, your type checking will complain. :) And the OP cleary knows they have a Date object, so no need to test for that either.
To test for an invalid date:
isNaN(date)
To test for a valid date:
!isNaN(date)
or (thanks to icc97 for this alternative)
isFinite(date)
or typescript (thanks to pat-migliaccio)
isFinite(+date)

// check whether date is valid
var t = new Date('2011-07-07T11:20:00.000+00:00x');
valid = !isNaN(t.valueOf());

I really liked Christoph's approach (but didn't have enough of a reputation to vote it up).
For my use, I know I will always have a Date object so I just extended date with a valid() method.
Date.prototype.valid = function() {
return isFinite(this);
}
Now I can just write this and it's much more descriptive than just checking isFinite in code...
d = new Date(userDate);
if (d.valid()) { /* do stuff */ }

I use the following code to validate values for year, month and date.
function createDate(year, month, _date) {
var d = new Date(year, month, _date);
if (d.getFullYear() != year
|| d.getMonth() != month
|| d.getDate() != _date) {
throw "invalid date";
}
return d;
}
For details, refer to Check date in javascript

you can check the valid format of txDate.value with this scirpt. if it was in incorrect format the Date obejct not instanced and return null to dt .
var dt = new Date(txtDate.value)
if (isNaN(dt))
And as #MiF's suggested in short way
if(isNaN(new Date(...)))

Too many complicated answers here already, but a simple line is sufficient (ES5):
Date.prototype.isValid = function (d) { return !isNaN(Date.parse(d)) } ;
or even in ES6 :
Date.prototype.isValid = d => !isNaN(Date.parse(d));

Why am I writing a 48th answer after so many have tried before me? Most of the answers are partly correct and will not work in every situation, while others are unnecessarily verbose and complex. Below is a very concise solution. This will checking if it is Date type and then check if a valid date object:
return x instanceof Date && !!x.getDate();
Now for parsing date Text: Most of the solutions use Date.parse(), or "new Date()" -- both of these will fail certain situations and can be dangerous. JavaScript parses a wide variety of formats and also is dependent on localization. For example, strings like "1" and "blah-123" will parse as a valid date.
Then there are posts that either use a ton of code, or a mile-long RegEx, or use third party frameworks.
This is dead simple method to validate a date string.
function isDate(txt) {
var matches = txt.match(/^\d?\d\/(\d?\d)\/\d{4}$/); //Note: "Day" in the RegEx is parenthesized
return !!matches && !!Date.parse(txt) && new Date(txt).getDate()==matches[1];
}
TEST THE FUNCTION
<br /><br />
<input id="dt" value = "12/21/2020">
<input type="button" value="validate" id="btnAction" onclick="document.getElementById('rslt').innerText = isDate(document.getElementById('dt').value)">
<br /><br />
Result: <span id="rslt"></span>
The first line of isDate parses the input text with a simple RegEx to validate for date formats mm/dd/yyyy, or m/d/yyyy. For other formats, you will need to change the RegEx accordingly, e.g. for dd-mm-yyyy the RegEx becomes /^(\d?\d)-\d?\d-\d{4}$/
If parse fails, "matches" is null, otherwise it stores the day-of-month. The second lines does more tests to ensure it is valid date and eliminates cases like 9/31/2021 (which JavaScript permits). Finally note the double-whack (!!) converts "falsy" to a boolean false.

This just worked for me
new Date('foo') == 'Invalid Date'; //is true
However this didn't work
new Date('foo') === 'Invalid Date'; //is false

None of these answers worked for me (tested in Safari 6.0) when trying to validate a date such as 2/31/2012, however, they work fine when trying any date greater than 31.
So I had to brute force a little. Assuming the date is in the format mm/dd/yyyy. I am using #broox answer:
Date.prototype.valid = function() {
return isFinite(this);
}
function validStringDate(value){
var d = new Date(value);
return d.valid() && value.split('/')[0] == (d.getMonth()+1);
}
validStringDate("2/29/2012"); // true (leap year)
validStringDate("2/29/2013"); // false
validStringDate("2/30/2012"); // false

For Angular.js projects you can use:
angular.isDate(myDate);

I wrote the following solution based on Borgar's solution. Included in my library of auxiliary functions, now it looks like this:
Object.isDate = function(obj) {
/// <summary>
/// Determines if the passed object is an instance of Date.
/// </summary>
/// <param name="obj">The object to test.</param>
return Object.prototype.toString.call(obj) === '[object Date]';
}
Object.isValidDate = function(obj) {
/// <summary>
/// Determines if the passed object is a Date object, containing an actual date.
/// </summary>
/// <param name="obj">The object to test.</param>
return Object.isDate(obj) && !isNaN(obj.getTime());
}

I rarely recommend libraries when one can do without. But considering the plethora of answers so far it seems worth pointing out that the popular library "date-fns" has a function isValid. The following documentation is taken from their website:
isValid argument
Before v2.0.0
v2.0.0 onward
new Date()
true
true
new Date('2016-01-01')
true
true
new Date('')
false
false
new Date(1488370835081)
true
true
new Date(NaN)
false
false
'2016-01-01'
TypeError
false
''
TypeError
false
1488370835081
TypeError
true
NaN
TypeError
false

Date.prototype.toISOString throws RangeError (at least in Chromium and Firefox) on invalid dates. You can use it as a means of validation and may not need isValidDate as such (EAFP). Otherwise it's:
function isValidDate(d)
{
try
{
d.toISOString();
return true;
}
catch(ex)
{
return false;
}
}

IsValidDate: function(date) {
var regex = /\d{1,2}\/\d{1,2}\/\d{4}/;
if (!regex.test(date)) return false;
var day = Number(date.split("/")[1]);
date = new Date(date);
if (date && date.getDate() != day) return false;
return true;
}

I've written this function. Pass it a string parameter and it will determine whether it's a valid date or not based on this format "dd/MM/yyyy".
here is a test
input: "hahaha",output: false.
input: "29/2/2000",output: true.
input: "29/2/2001",output: false.
function isValidDate(str) {
var parts = str.split('/');
if (parts.length < 3)
return false;
else {
var day = parseInt(parts[0]);
var month = parseInt(parts[1]);
var year = parseInt(parts[2]);
if (isNaN(day) || isNaN(month) || isNaN(year)) {
return false;
}
if (day < 1 || year < 1)
return false;
if(month>12||month<1)
return false;
if ((month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) && day > 31)
return false;
if ((month == 4 || month == 6 || month == 9 || month == 11 ) && day > 30)
return false;
if (month == 2) {
if (((year % 4) == 0 && (year % 100) != 0) || ((year % 400) == 0 && (year % 100) == 0)) {
if (day > 29)
return false;
} else {
if (day > 28)
return false;
}
}
return true;
}
}

None of the above solutions worked for me what did work however is
function validDate (d) {
var date = new Date(d);
var day = "" + date.getDate();
if ( day.length == 1 ) day = "0" + day;
var month = "" + (date.getMonth() + 1);
if ( month.length == 1 ) month = "0" + month;
var year = "" + date.getFullYear();
return (( month + "/" + day + "/" + year ) == d );
}
the code above will see when JS makes 02/31/2012 into 03/02/2012 that it's not valid

Date object to string is more simple and reliable way to detect if both fields are valid date.
e.g. If you enter this "-------" to the date input field. Some of the above answers won't work.
jQuery.validator.addMethod("greaterThan",
function(value, element, params) {
var startDate = new Date($(params).val());
var endDate = new Date(value);
if(startDate.toString() === 'Invalid Date' || endDate.toString() === 'Invalid Date') {
return false;
} else {
return endDate > startDate;
}
},'Must be greater than {0}.');

you can convert your date and time to milliseconds getTime()
this getTime() Method return Not a Number NaN when not valid
if(!isNaN(new Date("2012/25/255").getTime()))
return 'valid date time';
return 'Not a valid date time';

I combined the best performance results I found around that check if a given object:
is a Date instance (benchmark here)
has a valid date (benchmark here)
The result is the following:
function isValidDate(input) {
if(!(input && input.getTimezoneOffset && input.setUTCFullYear))
return false;
var time = input.getTime();
return time === time;
};

A ready function based on top rated answer:
/**
* Check if date exists and is valid.
*
* #param {String} dateString Date in YYYY-mm-dd format.
*/
function isValidDate(dateString) {
var isValid = false;
var date;
date =
new Date(
dateString);
if (
Object.prototype.toString.call(
date) === "[object Date]") {
if (isNaN(date.getTime())) {
// Date is unreal.
} else {
// Date is real if month and day match each other in date and string (otherwise may be shifted):
isValid =
date.getUTCMonth() + 1 === dateString.split("-")[1] * 1 &&
date.getUTCDate() === dateString.split("-")[2] * 1;
}
} else {
// It's not a date.
}
return isValid;
}

No one has mentioned it yet, so Symbols would also be a way to go:
Symbol.for(new Date("Peter")) === Symbol.for("Invalid Date") // true
Symbol.for(new Date()) === Symbol.for("Invalid Date") // false
console.log('Symbol.for(new Date("Peter")) === Symbol.for("Invalid Date")', Symbol.for(new Date("Peter")) === Symbol.for("Invalid Date")) // true
console.log('Symbol.for(new Date()) === Symbol.for("Invalid Date")', Symbol.for(new Date()) === Symbol.for("Invalid Date")) // false
Be aware of:
https://caniuse.com/#search=Symbol

Inspired by Borgar's approach I made sure that the code not only validates the date, but actually makes sure the date is a real date, meaning that dates like 31/09/2011 and 29/02/2011 are not allowed.
function(dateStr) {
s = dateStr.split('/');
d = new Date(+s[2], s[1] - 1, +s[0]);
if (Object.prototype.toString.call(d) === "[object Date]") {
if (!isNaN(d.getTime()) && d.getDate() == s[0] &&
d.getMonth() == (s[1] - 1)) {
return true;
}
}
return "Invalid date!";
}

Related

How to test a string is valid date or not using moment?

I would like to test if a date and or time entered is valid.
Can this be done with moment as date and time testing with javascript seems a nightmare. (have spent hours on this).
Test data looks like this.
Invalid
invalid = ""
invalid = " "
invalid = "x"
invalid = "1/1"
invalid = "30/2/2015"
invalid = "2/30/2015"
Is Valid
isvalid = "1/12/2015"
isvalid = "1/12/2015 1:00 PM";
Have tried various javascript methods with hours of trials failing.
I thought moment would have something for this. So tried the following, all of which does not work because I do no think moment works like this.
var valid = moment(input).isDate()
var valid = moment().isDate(input)
My time format is "dd/mm/yyyy"
Moment has a function called isValid.
You want to use this function along with the target date format and the strict parsing parameter to true (otherwise your validation might not be consistent) to delegate to the library all the needed checks (like leap years):
var dateFormat = "DD/MM/YYYY";
moment("28/02/2011", dateFormat, true).isValid(); // return true
moment("29/02/2011", dateFormat, true).isValid(); // return false: February 29th of 2011 does not exist, because 2011 is not a leap year
Yes, you could use momentjs to parse it and compare it back with the string
function isValidDate(str) {
var d = moment(str,'D/M/YYYY');
if(d == null || !d.isValid()) return false;
return str.indexOf(d.format('D/M/YYYY')) >= 0
|| str.indexOf(d.format('DD/MM/YYYY')) >= 0
|| str.indexOf(d.format('D/M/YY')) >= 0
|| str.indexOf(d.format('DD/MM/YY')) >= 0;
}
Test code
tests = ['',' ','x','1/1','1/12/2015','1/12/2015 1:00 PM']
for(var z in tests) {
var test = tests[z];
console.log('"' + test + '" ' + isValidDate(test));
}
Output
"" false
" " false
"x" false
"1/1" false
"1/12/2015" true
"1/12/2015 1:00 PM" true
You can use the Date.parse() function.
Here is the details of how to use.

Date Validation - how to work around Javascript's auto-correcting of dates?

I want to validate dates by Javascript and found this nice answer:
https://stackoverflow.com/a/1353711/3391783
but when i try to use it to validate dates, it seems like Javascript is auto-correcting my date by taking the closest valid date. so this will return true even though 2014-11-31 is not a valid date (Javascript months start at 0, so 10 equals November):
function isValidDate(d) {
if ( Object.prototype.toString.call(d) !== "[object Date]" )
return false;
return !isNaN(d.getTime());
}
var test_date = new Date(2014, 10, 31);
console.log( test_date );
console.log( isValidDate(test_date) );
seems like creating the Date is automatically switching it to 2014-12-01 which is a correct date.
but I would like to be able to validate user input without changing it.
So how can i create an invalid new Date() in Javascript?
Or is there a much simpler way to do this?
You can use the auto-correction in the Date object to validate the date. Just check the input against what you have in the Date object:
var y = 2014, m = 10, d = 31;
var test_date = new Date(y, m, d);
var valid =
test_date.getFullYear() == y &&
test_date.getMonth() == m &&
test_date.getDate() == d;
document.write(valid);
When it comes to handling dates in JavaScript, I'm a big fan of Moment.js. As you can see here, they do a good job of validating dates: http://momentjs.com/docs/#/parsing/is-valid/
new Date(2013, 25, 14).toString(); // "Sat Feb 14 2015 00:00:00 GMT-0500 (EST)"
moment([2015, 25, 35]).format(); // 'Invalid date'
Here's a function I wrote a while back that demonstrates Guffa's solution.
function isValidDate(checkDate) {
if(!/\d\d\/\d\d\/\d\d\d\d/.test(checkDate)) {
return false; // checkDate is not formatted as ##/##/####
} else {
// split checkDate into three pieces
var strMM = checkDate.split('/')[0];
var strDD = checkDate.split('/')[1];
var strYYYY = checkDate.split('/')[2];
// create new Date() object from split pieces
var strDateCheck = new Date(strYYYY,(strMM - 1),strDD);
// evaluate each piece of resulting date object against each corresponding piece of checkDate
if(((strDateCheck.getMonth() + 1) == strMM) && (strDateCheck.getDate() == strDD) && (strDateCheck.getFullYear() == strYYYY)) {
/* if you wish, add additional validation constraints here */
return true; // all three pieces match exactly
} else {
return false; // at least one piece did not match
}
}
}

Javascript date of birth conundrum

I need to validate a primitive date of birth field input in the format of:
'mmmyyyy'
Where the first 3 characters of the string must be an acceptable 3-letter abbreviation of the months of the year.
It can be lowercase, or uppercase, or a mix of any so long as it spells out jan or feb or mar etc etc etc.
There is no built-in method that I am aware of that has a ready array of this specific format of a month to be able compare against user input. I was thinking that I could maybe use the localeCompare() method in a for loop to test if the output is not 0 then append an error message accordingly.
function dateTester() {
var d = new Date(),
i,
mo = [],
moIsValid;
for (i = 0; i < 12; i += 1) {
d.setMonth(i);
mo.push(d.toLocaleString().split(' ')[1].substr(0, 3));
}
return new RegExp('^(' + mo.join('|') + ')', 'i');
}
var moIsValid = dateTester();
alert(moIsValid.test('fEb1992'));
If you don't want the user's current locale name for the days to be valid, then just switch toLocaleString() to toString(). But then, why don't you just do this instead:
var moIsValid = /^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i;
alert(moIsValid.test('fEb1992'));
I like this concise function for validating your input:
var months = "janfebmaraprmayjunjulaugsepoctnovdec";
function validate(dateString) {
return dateString.length == 7 &&
!(months.indexOf(dateString.substr(0,3).toLowerCase()) % 3) &&
isFinite(dateString.substr(3));
}
http://jsfiddle.net/gilly3/NR3aG/
Unless you just really, really want to check a month with a "dynamic" test, you can do:
var months = 'jan,feb,mar,apr,may,jun,jul,aug,sep,oct,nov,dec';
months.indexOf('JaN1975'.toLowerCase().substring(0,3)
Checking with:
console.log(months.indexOf('JaN1975'.toLowerCase().substring(0,3)) != -1);
console.log(months.indexOf('oct1975'.toLowerCase().substring(0,3)) != -1);
console.log(months.indexOf('FEB1975'.toLowerCase().substring(0,3)) != -1);
console.log(months.indexOf('Ja1975'.toLowerCase().substring(0,3)) != -1);
console.log(months.indexOf('091975'.toLowerCase().substring(0,3)) != -1);
http://jsfiddle.net/ELMFu/
Gives:
true
true
true
false
false
new Date(str.replace(/(\D+)(\d+)/, "1 $1 $2"))
EDIT: use isNaN to test whether the date failed to parse.

Compare dates javascript

I need to validate different date's with some javascript(jquery).
I have a textbox with, the inputmask from jquery (http://plugins.jquery.com/plugin-tags/inputmask). The mask that i use is "d/m/y".
Now i have set up a CustomValidator function to validate the date.
I need 2 functions. One to check if the given date is greater then 18 years ago. You must be older then 18 year.
One function to check if the date is not in the future. It can only in the past.
The function are like
function OlderThen18(source, args) {
}
function DateInThePast(source, args) {
}
As you know the value you get back with args.Value is 27/12/1987 .
But how can i check this date in the functions? So that i can set args.IsValid to True or False.
I tried to parse the string(27/12/1987) that i get back from the masked textbox to a date but i get always a value back like 27/12/1988.
So how could I check the given dates with the other dates?
The simple way is to add 18 years to the supplied date and see if the result is today or earlier, e.g.:
// Input date as d/m/y or date object
// Return true/false if d is 18 years or more ago
function isOver18(d) {
var t;
var now = new Date();
// Set hours, mins, secs to zero
now.setHours(0,0,0);
// Deal with string input
if (typeof d == 'string') {
t = d.split('/');
d = new Date(t[2] + '/' + t[1] + '/' + t[0]);
}
// Add 18 years to date, check if on or before today
if (d.setYear && d.getFullYear) {
d.setYear(d.getFullYear() + 18);
}
return d <= now;
}
// For 27/4/2011
isOver18('27/4/2011'); // true
isOver18('26/4/2011'); // true
isOver18('28/4/2011'); // false
try this to start:
var d = new Date(myDate);
var now = new Date();
if ((now.getFullYear() - d.getFullYear()) < 18) {
//do stuff
}
The javascript date object is quite flexible and can handle many date strings.
You can compare two Date objects or use the Date interface methods, such as getSeconds() of getFullYear() in order to deduce useful data regarding the date.
See Date object reference formore details.
You'll need to construct, modify and compare Date objects - something like this:
// str should already be in dd/mm/yyyy format
function parseDate(str) {
var a = str.split('/');
return new Date(parseInt(a[2], 10), // year
parseInt(a[1], 10) - 1, // month, should be 0-11
parseInt(a[0], 10)); // day
}
// returns a date object for today (at midnight)
function today() {
var date = new Date();
date.setHours(0, 0, 0);
return date;
}
function DateInThePast(str) {
// date objects can be compared like numbers
// for equality (==) you'll need to compare the value of date.getTime()
return parseDate(str) < today();
}
function OlderThan18(str) {
// left as an exercise for the reader :-)
}

JavaScript - Validate Date

I have an HTML text field. I want to validate via JavaScript that the value entered is a valid date in the form of "MM/DD/YY" or "MM/D/YY" or "MM/DD/YYYY" or "MM/D/YYYY". Is there a function that does this?
I sort of assumed there was something like isNaN but I don't see anything. Is it true that JavaScript can't validate dates?
You could use javascript's own Date object to check the date. Since the date object allows some mucking around with the month and day values (for example March 32 would be corrected to April 1), you can just check that the date you create matches the one you put in. You could shorten this if you want, but it's longer for clarity.
function checkDate(m,d,y)
{
try {
// create the date object with the values sent in (month is zero based)
var dt = new Date(y,m-1,d,0,0,0,0);
// get the month, day, and year from the object we just created
var mon = dt.getMonth() + 1;
var day = dt.getDate();
var yr = dt.getYear() + 1900;
// if they match then the date is valid
if ( mon == m && yr == y && day == d )
return true;
else
return false;
}
catch(e) {
return false;
}
}
Is it true that JavaScript can't validate dates?
No.
Is there a function that does this?
No.
You will need to write your own validation function to parse the date format (regex comes to mind) and then determine if it is valid within your specific criteria.
Check out http://momentjs.com/. Using it, this snippet
moment(yourCandidateString, 'MM-DD-YYYY').isValid()
should do the job.
This is what I use to validate a date.
Date.parse returns NaN for invalid dates.
This supports both date-only and date+time formats.
Hope this helps.
var msg;
var str = "2013-12-04 23:10:59";
str = "2012/12/42";
var resp = Date.parse(str);
if(!isNaN(resp)) { msg='valid date'; } else { msg='invalid date'; }
console.log(msg);
If you want to venture into the realms of JQuery there are plenty of validation plugins that include date validation. This plugin is one I've used a few times and has served me well.
I use Bootstrap Datepicker. One of the options with the text box disabled should do the trick.
http://www.eyecon.ro/bootstrap-datepicker/
<input type="text" id="dateinput"/>
<script type="text/javascript">
$(#"dateinput").datepicker({
buttonImage: "images/calendar.png",
dateFormat: "yyyy-MMM-dd"
});
function validateDate() {
if ($(#"dateinput").val().trim() == "") {
// Is a blank date allowed?
return true;
}
var oldVal = $(#"dateinput").val(); // Current value in textbox
// Now use jQueryUI datepicker to try and set the date with the current textbox value
$(#"dateinput").datepicker("setDate",$(#"dateinput").val());
// Check if the textbox value has changed
if (oldVal != $(#"dateinput").val()) {
// The datepicker will set something different if the date is invalid
$(#"dateinput").val(oldVal); // Set the textbox back to the invalid date
alert ("date was invalid");
return false;
} else {
// If nothing changed, the date must be good.
return true;
}
}
</script>
There does not appear to be a build-in function which does that. However, this code is probably what you're looking for:
<script type="text/javascript">
/**--------------------------
//* Validate Date Field script- By JavaScriptKit.com
//* For this script and 100s more, visit http://www.javascriptkit.com
//* This notice must stay intact for usage
---------------------------**/
function checkdate(input){
var validformat=/^\d{2}\/\d{2}\/\d{4}$/ //Basic check for format validity
var returnval=false
if (!validformat.test(input.value))
alert("Invalid Date Format. Please correct and submit again.")
else{ //Detailed check for valid date ranges
var monthfield=input.value.split("/")[0]
var dayfield=input.value.split("/")[1]
var yearfield=input.value.split("/")[2]
var dayobj = new Date(yearfield, monthfield-1, dayfield)
if ((dayobj.getMonth()+1!=monthfield)||(dayobj.getDate()!=dayfield)||(dayobj.getFullYear()!=yearfield))
alert("Invalid Day, Month, or Year range detected. Please correct and submit again.")
else
returnval=true
}
if (returnval==false) input.select()
return returnval
}
</script>
Source: http://www.javascriptkit.com/script/script2/validatedate.shtml
Have you googled for something like javascript date validation? It shows up some good information, and a working code example here.
I suggest you a couple of solutions.
guide the user input with a date picker. This way you can control the input format. jQueryui datepicker is a popular implementation.
use a js library to manage datetime data type (not an actual datatype in Javascript!!). I suggest you date.js.
Similar to this answer, Date can be used to check if the parsed version of the string corresponds to the original date string.
> datestring_valid = "2020-02-29";
> parsed_Date = new Date(datestring_valid);
> parsed_Date.toISOString().slice(0,10) == datestring_valid;
true
> datestring_invalid = "2021-02-29";
> parsed_Date = new Date(datestring_invalid);
> parsed_Date.toISOString().slice(0,10) == datestring_invalid;
false
NB: This requires the date string to be ISO formatted.
The reason this works is, that Date parses some invalid dates into something valid as in the example above. However, supplying "2020-01-32" into Date will result in the result being "Invalid Date" that isNaN.
A function that handles all of this is the following:
function isValidDateString(datestring) {
parsed_Date = new Date(datestring);
return (parsed_Date.toISOString().slice(0,10) == datestring) && !isNaN(parsed_Date)
};
> isValidDateString(datestring_valid)
true
> isValidDateString(datestring_invalid)
false

Categories

Resources