Javascript date of birth conundrum - javascript

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.

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
}
}
}

Need to validate dd/mm/yy hh:mmtt in Javascript

I am trying this to validate the date.However I am not too sure about what is wrong with this.
Note- I my application there is no space between mm(minuted) and AM/PM.
var date = '21/01/13 6:40AM';
var myRegex = /0?[0-31]\d\/0?[0-12]\d\/\d{2} [0-11]\d:[0-59]\d[AP][M]/;
if (myRegex.test(date)){
// Ok to proceed
}
I tried the following by breaking the date and time separately i.e the following combination
var date = '21/01/13'
var myRegex = /0?[0-31]\d\/0?[0-12]\d\/d{2}/;
However for the time part i.e 6:40AM.I am not able to validate it with
var myRegex = /[0-11]\d:[0-59]\d[AP][M]/;
Could you please help me out.
Try This One. Leap year supported. example: http://jsfiddle.net/Vk268/
^(((0[1-9]|[12]\d|3[01])\/(0[13578]|1[02])\/((19|[2-9]\d)\d{2}))|((0[1-9]|[12]\d|30)\/(0[13456789]|1[012])\/((19|[2-9]\d)\d{2}))|((0[1-9]|1\d|2[0-8])\/02\/((19|[2-9]\d)\d{2}))|(29\/02\/((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))$
Try This :
var regex = /^([0-11]\d):([0-59]\d)\s?(?:AM|PM)?$/i;
Will work for : "06:40am"
I suggest you to check actual validity not just syntax. check this post which uses datejs
Jquery DateJs, is there validation for full date?
One way to validate date and time strings is to create a date object and see if the parts match, e.g.
function validateDateString(s) {
var b = s.split(/[\/ :]/g);
var ap = s.substring(-2).toLowerCase();
var h = parseInt(b[3], 10) + (ap == 'am'? 0 : 12);
var min = parseInt(b[4],0);
var y = +b[2] + (b[2] < 50? 2000 : 1900);
var d = new Date(y, --b[1], b[0], h, min, 0, 0);
var apValid = /am|pm/.test(ap);
// Only need to test two parts of date and hours
return d.getMonth() == b[1] && d.getDate() == b[0] && d.getHours() == h && apValid;
}
console.log(validateDateString('21/01/13 6:40AM')); // true
You could use a regular expression too, and if ES5 compliant browsers are all you need to support you could reformat the string as an ISO 8601 compliant string a pass it to Date.parse. But that won't work in many browsers in use.

Validate two dates of this "dd-MMM-yyyy" format in javascript

I have two dates 18-Aug-2010 and 19-Aug-2010 of this format. How to find whether which date is greater?
You will need to create a custom parsing function to handle the format you want, and get date objects to compare, for example:
function customParse(str) {
var months = ['Jan','Feb','Mar','Apr','May','Jun',
'Jul','Aug','Sep','Oct','Nov','Dec'],
n = months.length, re = /(\d{2})-([a-z]{3})-(\d{4})/i, matches;
while(n--) { months[months[n]]=n; } // map month names to their index :)
matches = str.match(re); // extract date parts from string
return new Date(matches[3], months[matches[2]], matches[1]);
}
customParse("18-Aug-2010");
// "Wed Aug 18 2010 00:00:00"
customParse("19-Aug-2010") > customParse("18-Aug-2010");
// true
You can do the parsing manually, for your given format, but I'd suggest you use the date.js library to parse the dates to Date objects and then compare.
Check it out, its awesome!
And moreover, its a great addition to your js utility toolbox.
The native Date can parse "MMM+ dd yyyy", which gives:
function parseDMY(s){
return new Date(s.replace(/^(\d+)\W+(\w+)\W+/, '$2 $1 '));
}
+parseDMY('19-August-2010') == +new Date(2010, 7, 19) // true
parseDMY('18-Aug-2010') < parseDMY('19-Aug-2010') // true
Firstly, the 'dd-MMM-yyyy' format isn't an accepted input format of the Date constructor (it returns an "invalid date" object) so we need to parse this ourselves. Let's write a function to return a Date object from a string in this format.
function parseMyDate(s) {
var m = ['jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec'];
var match = s.match(/(\d+)-([^.]+)-(\d+)/);
var date = match[1];
var monthText = match[2];
var year = match[3];
var month = m.indexOf(monthText.toLowerCase());
return new Date(year, month, date);
}
Date objects implicitly typecast to a number (milliseconds since 1970; epoch time) so you can compare using normal comparison operators:
if (parseMyDate(date1) > parseMyDate(date2)) ...
Update: IE10, FX30 (and likely more) will understand "18 Aug 2010" without the dashes - Chrome handles either
so Date.parse("18-Aug-2010".replace("/-/g," ")) works in these browsers (and more)
Live Demo
Hence
function compareDates(str1,str2) {
var d1 = Date.parse(str1.replace("/-/g," ")),
d2 = Date.parse(str2.replace("/-/g," "));
return d1<d2;
}

Detecting an "invalid date" Date instance in 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!";
}

Categories

Resources