0

I am using below code to create date object after accepting date string from user in MM/DD/YYYY string format.

var userEnteredDate = '02/31/2015'; //example incorrect date entered by user
var userDate = new Date(userEnteredDate); //Getting rounded to 3rd March instead of throwing error

Is there any way to fix this in JavaScript. I would not like to do all the validations for Leap years, Date missing from Gregorian Calendar etc.

The required behavior is it should return NaN when passing wrong date. I do not want to use any third party library for compatibility reason with older version of angularjs.

**Note:**This is different than using Momentjs, this question is about the issue in javascript date functionality

Amit Mahajan
  • 895
  • 6
  • 34

1 Answers1

1

Date parsing using the native Date constructor is unreliable. You should use the Moment.js library instead – it throws errors for invalid dates.

If you're allowing a user to input dates, you may also consider using a datepicker for better UX.

Michał Perłakowski
  • 88,409
  • 26
  • 156
  • 177
  • Hi, It seems we have some issues in using momentjs library due to existing older version of javascripts used in our project. – Amit Mahajan Jun 09 '17 at 04:33