I am using react-datetime for our calendar control.Now the issue is that if the user entered an invalid date like 'djfdjfhjkhdf' then in this control nothing is there to validate.So I decided to write my own validation function and call that on blur event if the date is invalid then clear the text entered by the user.My code is like this:-
import DatePicker from 'react-datetime';
focousOut(value) {
if (!validateDate(value)) {
this.setState({ startDate: ''});
this.setState({ selectedValue: '' });
}
}
handleChange(date) {
this.setState({ selectedValue: date });
this.setState({ startDate: date });
}
<Datetime
timeFormat={false}
value={this.state.selectedValue}
defaultValue={this.state.startDate}
onChange={this.handleChange}
onBlur={this.focousOut}
locale='en-US'
dateFormat
closeOnSelect
/>
One of the issues seem to be that, based on the given props, you are creating a mix of a controlled and uncontrolled
Datetime
component. Basically, usevalue
if you want a state-controlled component, ordefaultValue
to let the DOM manage the input value.See this part of the documentation:
Have a look at this forked codepen I made.
Also, you can use the
moment.js
library to easily determine if a string is of a valid Date format. Just usemoment().isValid()
.I should note that the
onBlur
event seems to trigger on the 2nd blur. Not sure why that is, but perhaps the you'll find an answer in the docs. The above is only a fix to your existing code, and hopefully a useful guideline to get you started.