Reputation: 1060
I'm building a date picker React component, where a user can type the day, month, year or select it from a calendar.
I'm being lazy and seeing if the date is valid for the text input by using:
validateDate(event) {
const { selectedDay, selectedMonth, selectedYear } = this.state;
const checkDateIsValid = new Date(
selectedMonth.toString() + '/' +
selectedDay.toString() + '/' +
selectedYear.toString());
if (checkDateIsValid == 'Invalid Date') {
this.setState({ validDate: false });
}
else {
this.setState({ validDate: true });
}
}
However, there's a issue where an invalid date of the 31st of February will create a valid Date object of '3rd March...'. I know I can get input validation by manually comparing the day and month field to see if you can have valid matches, but I'm wondering if there is a quicker way of doing that? Thanks in advance
Upvotes: 1
Views: 241
Reputation: 1520
You can simply use Moment.js to check whether the date is valid or not. I don't know why you are splitting date and joining. But it will helps you!
var date = moment(YOUR_DATE_STRING); // For example --> moment('2017-11-22')
if(date.isValid()) {
this.setState({ validDate: true });
}
else {
this.setState({ validDate: false });
}
Upvotes: 2