Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clear the value entered in react-datepicker?

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?

like image 353
Gorakh Nath Avatar asked Sep 04 '17 11:09

Gorakh Nath


Video Answer


1 Answers

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.

like image 91
Gorakh Nath Avatar answered Oct 27 '22 01:10

Gorakh Nath