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
/>
Instead of selected , change it to value . Then set its value to empty string if you want to clear it.
To disable the past and future dates, we have to use the isValidDate property of the react-datetime.
Yeah, there's clearly a rendering bug in component if you try to pass a null or empty value in controlled component mode: the internal input still got the former value entered with the calendar (uncontrolled ?) despite the fact that that.state.value is null : I've been able to "patch" it with the renderInput prop :
<Datetime
value={(this.state.date) ? this.state.date : ''}
onChange={(value) => { this.setState{(date : ((value) && (isNaN(new Date(value)) === false)) ? new Date(value)).format('yyyy-mm-dd') null, attribute) }}
renderInput={(props) => {
return <input {...props} value={(this.state.date) ? props.value : ''} />
}}
/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With