How to clear the value entered in react-datepicker?

25.4k views Asked by At

I am using react-datepicker 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-datepicker';
import 'react-datepicker/dist/react-datepicker.css';
focousOut(value) {
 this.handleChange('');
}
handleChange(date) {
 this.setState({ selectedValue: date });
 this.setState({ startDate: date });
}

<DatePicker
 selected={this.state.selectedValue}
 value={this.state.startDate}
 onChange={this.handleChange}
 onBlur={event => this.focousOut(event.target.value)} />

validateDate is a function that will return true or false, iff the date is valid then true else return false. How can I achieve this requirement, can you please assist me?

1

There are 1 answers

0
Gorakh Nath On

I found the solution first add the control as:

<DatePicker
   selected={this.state.selectedValue}
   value={this.state.startDate}
   onChange={this.handleChange}
   onChangeRaw={(event) =>
   this.handleChangeRaw(event.target.value)}
   onBlur={event => this.focousOut(event.target.value)}
  />

Now, for the event add the following code:

handleChangeRaw(value) {
 this.setState({ startDate: value });
}
handleChange(date) {
 this.setState({ selectedValue: date });
}
focousOut(value) {
if (!validateDate(value)) {
    this.setState({ startDate: '' });
    this.setState({ selectedValue: moment() });
   }
}

validateDate is the function use for validating the date. If it returns false means invalid date, in this case resetting the value to initial state.