Reputation: 730
I want to check whether a date is valid given a given format in JavaScript. In essence I'd like to see of a string can be parsed to the given format. Since Date.parse doesnt take a format string i can't figure out how to do this
Date.parse('01/21/2017','dd/mm/yyyy') //should return null
Date.parse('21/01/2017','dd/mm/yyyy') //should return date
Upvotes: 0
Views: 541
Reputation: 8193
Date.parse(dateString) method has only one parameter
dateString - accept a string representing an RFC2822 or ISO 8601 date format (other formats may be used, but results may be unexpected ")
To parse and validate a string you can use an external library like moment.js
.
console.log(moment('01/21/2017', 'DD/MM/YYYY', true).isValid());
console.log(moment('21/01/2017', 'DD/MM/YYYY', true).isValid());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.js"></script>
Upvotes: 1
Reputation: 1670
I do not think this is a proper use case of validating it with the format.
Because
dd/mm/yyyy
format and 04/03/2017 in mm/dd/yyyy
format.Now if you consider validating this scenario, you never know what the input actually meant it might be 3rd April 2017 or 4th March 2017 in your scenario.
Consider date 23rd March 2017.
Now try new Date('23/03/2017')
This would return you null. Javascript date returns you date object if the input was correct, i.e., it is expecting yyyy/mm/dd
or mm/dd/yyyy
console.log(new Date('23/03/2017'));
moment.js
which has some decent functions like comparing them with the format of the date input. var x = '03/23/2017';
console.log(moment(x, 'DD/MM/YYYY', true).isValid());
console.log(moment(x, 'MM/DD/YYYY', true).isValid());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>
hope this helps you!
Upvotes: 3
Reputation: 346
If its possible to use moment.js
, you can do something like
function parseDate(dateString, format){
if (moment(dateString,format).isValid())
return moment(dateString, format).toDate();
else
return null;
}
Upvotes: 2