JavaScript validation date

I get three variables through user input, which contains the year of the date, month, and day. I already checked if the month var from 1 to 12 exists, etc.

Now I want to check if this is a real date, and not a date that does not exist, for example, 06/31/2011.

My first idea was to create a new Date instance:

var year = 2011; var month = 5; // five because the months start with 0 in JavaScript - June var day = 31; var myDate = new Date(2011,5,31); console.log(myDate); 

But myDate does not return false because it is not a valid date. Instead, it returns "Fri Jul 01 2011 [...]".

Any ideas how I can check for an invalid date?

+6
source share
4 answers

Try the following:

 if ((myDate.getMonth()+1!=month)||(myDate.getDate()!=day)||(myDate.getFullYear()!=year)) alert("Date Invalid."); 
+11
source
 if ((myDate.getDate() != day) || (myDate.getMonth() != month - 1) || (myDate.getFullYear() != year)) { return false; } 

JavaScript simply converts the month , year , day , etc. constructor introduced into the Date constructor. into a simple int value (milliseconds), and then formats it for presentation in string format. You can create a new Date(2011, 100, 100) , and everythig will be fine :)

+5
source

Now you can do what you are doing and create a new Date object and then check the value of myDate.getFullYear (), myDate.getMonth (), myDate.getDate () to make sure that these values ​​match the input of the value. Keep in mind that getMonth () and getDate () are indexed to 0, so January is month 0 and December is month 11.

Here is an example:

 function isValidDate(year, month, day) { var d = new Date(year, month, day); return d.getFullYear() === year && d.getMonth() === month && d.getDate() === day; } console.log(isValidDate(2011,5,31)); console.log(isValidDate(2011,5,30)); 
0
source

I think so.

 function isValidDate(year, month, day) { var d = new Date(year, month, day); if(month == 12){ year = parseInt(year)*1+1*1; month = 0; } day = parseInt(day); month = parseInt(month); year = parseInt(year); if(month === 2 && day > 29){ return false; } return d.getFullYear() === year && d.getMonth() === month && d.getDate() === day; } 
0
source

Source: https://habr.com/ru/post/893409/


All Articles