react-datepicker icon indicating copy to clipboard operation
react-datepicker copied to clipboard

Impossible to validate with manual input

Open jchitel opened this issue 8 years ago • 18 comments

I've used this library before, and it's worked great, except for one case.

The user is allowed to enter manual input (unless the readOnly prop is set to true, but that impacts UX, so I'd prefer to not do that). However, the date parsing logic inside this library will ignore any invalid inputs and not propagate change events for invalid dates.

What this means is that there is a disconnect from what the user sees and what the component reflects to the caller. The user could enter "awehfoiajfoa" into the input, but the caller will still have the previous valid date. ~~There is absolutely no way to validate arbitrary input.~~ (see next comment)

Here are potential solutions:

  • The component fires onChange any time the input changes instead of only in the case of a valid date. Instead of returning null from parseDate, you can return the invalid moment instance. This will allow developers to simply check the isValid() method on the moment instance to do validation.
  • Abstract the date/time library used, have the API just use strings, and still fire onChange on every input change. The developer won't be required to use moment and can just use their own validation processes. The dateFormat and timeFormat props can control how the component internally parses and formats the dates.
  • Add validation functionality. In the case of an invalid parse, the component can fire some onValidate event that will pass a boolean for whether the user's input is valid, or perhaps an error message. This will allow the developer to respond to invalid input by toggling classes, disabling submit buttons, etc.
  • Add a prop enableManualInput to allow the user to manually edit the value. This should be defaulted to false so that the developer can guarantee that there will always be a valid date, as the user can't enter anything else.

In any case, it is ~~impossible~~ (not impossible, see next comment) for a developer to validate this component, and this is something the component should enable.

jchitel avatar Mar 27 '18 20:03 jchitel

Ah, I seem to have spoken a bit too soon. I didn't notice the onChangeRaw prop, which behaves similarly to my second suggestion.

However, I do think that a discussion around validation is warranted. A developer should not have to use an API labelled "raw" to add validation logic to a component.

jchitel avatar Mar 27 '18 21:03 jchitel

No, I think you were right the first time.

Even if you detect that something is invalid in your onChangeRaw handler, what are you supposed to do about it? You can't stomp the user's input as they're typing.

And you can't do it in onBlur, because they might not have been typing, or, they might have stopped typing halfway through and ended up clicking on a date (in which case whatever "input value" you had been keeping track of will be stale).

Maybe there's some combination of refs, changeRaw, onBlur, onSelect, onChange and weird state setting and tracking that you can wrangle together to accomplish this, but it won't be pretty, and it won't be easy.

It might even be impossible.

How could something so important be so overlooked?

sarink avatar Apr 12 '18 01:04 sarink

Even if you detect that something is invalid in your onChangeRaw handler, what are you supposed to do about it? You can't stomp the user's input as they're typing.

jchitel is correct in that you can use onChangeRaw as a workaround, as long as you simply do nothing on invalid input.

It's not intuitive though as normally when you have a "controlled" form component in React, you would pass in the value as a prop, and the form element would never change except on prop value change. react-datepicker works both like a controlled and also uncontrolled component, as you can edit the field, and it keeps local state independent of the state value passed into it as a prop. OTOH, updating the value prop clobbers the local DatePicker edit state.

Below is my app specific wrapper component that seems to work as expected:

class DateTimePicker extends React.Component {
  onChangeRaw = (e) => {
    let m = moment(e.target.value);
    if (m.isValid()) {
      this.props.onChange(m);
    }
  };

  render() {
    return <DatePicker
      className="form-control"
      selected={this.props.selected}
      onChange={this.props.onChange}
      onChangeRaw={this.onChangeRaw}
      showTimeSelect
      dateFormat="LLL"
    />
  }
}

KennyMonster avatar May 04 '18 19:05 KennyMonster

Great datepicker tool. I am running into this problem as well. My users can enter an invalid date manually and never know it. What I would like is for the manually entered date to be parsed if possible and reformatted in the input field for the user to see. If it can't be parsed, then the input value (and selected value) should be cleared. Other than this issue of manually entered dates, the datepicker is working well!

benjaminkniaz avatar Aug 03 '18 03:08 benjaminkniaz

I've used the value property along with onChangeRaw and onBlur to achieve what I want (see below). Seems to work so far.

It would be great if this kind of thing could be included out-of-the-box. Looking around at other react date pickers, I don't see that they validate the manual entry either.

<DatePicker
    selected={props.beg_inv_dt}
    onChange={props.handleBegDateChange}
    onChangeRaw={event =>
        props.handleBegDateChangeRaw(event.target.value)
    }
    onBlur={e => props.handleBegDateBlur(e.target.value)}
    placeholderText="MM/DD/YYYY"
    value={props.beg_inv_dt_display}
/>

// then in my controller ...

handleBegDateChange(date) {
    if (date !== null) {
        let dateFormat = date.format("MM/DD/YYYY");
        this.setState({ beg_inv_dt: date, beg_inv_dt_display: dateFormat });
    }
}

handleBegDateChangeRaw(value) {
    this.setState({ beg_inv_dt_display: value });
}

handleBegDateBlur(value) {
    var date = moment(value, "MM/DD/YYYY");
    if (date.isValid() === false) {
        this.setState({
            beg_inv_dt: null,
            beg_inv_dt_display: ""
        });
    } else {
        this.setState({
            beg_inv_dt: date,
            beg_inv_dt_display: date.format("MM/DD/YYYY")
        });
    }
}

benjaminkniaz avatar Aug 03 '18 03:08 benjaminkniaz

+1, we had to write some janky code to get this to work properly, would be great to have this as default behavior

pklada avatar Oct 05 '18 23:10 pklada

I agree, the user should not be allowed to enter an invalid date/time. I am looking for a date-time picker component that acts as the one in the official macOS calendar app, but I did not find yet something that robust. Don't get me wrong, this is great work, but the following two improvements are for me foundamental:

  • when the user clicks on a date or time component (eg. the month), the month digits are highlighted such that I can start typing a new month number and it will not just add text to the existing one (invalidating the input) but rather replace it
  • forbid any invalid value for dates and times The following is Apple date picker, no way one can insert an invalid date. screen shot 2018-10-13 at 19 27 19

marcoancona avatar Oct 13 '18 17:10 marcoancona

+1

Peterabsolon avatar Nov 21 '18 16:11 Peterabsolon

+1

pbsmultimedia avatar May 07 '19 15:05 pbsmultimedia

Hi, I'm having the same issue too and I am using DateRangePicker. onChangeRaw is not working for DateRangePicker. Does anyone have any idea about it, or what would be the best solution in my case? PS: As I mentioned I'm using DateRangePicker instead of DatePicker.

turanserin avatar Jun 26 '19 21:06 turanserin

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

stale[bot] avatar Dec 23 '19 22:12 stale[bot]

+1

HerbertSu avatar Mar 26 '20 20:03 HerbertSu

+1

NikolaStanisavljevic avatar Feb 04 '21 13:02 NikolaStanisavljevic

+1

aligreene avatar Dec 23 '21 15:12 aligreene

+1

srinivasraja54 avatar Dec 30 '21 12:12 srinivasraja54

+1

eliashkan avatar Jan 24 '22 15:01 eliashkan

+1

nicole-ilustre avatar May 12 '22 03:05 nicole-ilustre

event.target.value

onChangeRaw={event => props.handleBegDateChangeRaw(event.target.value) } The target element is div element and has no value. That's why I can not get the value and validity on Input from the event. So far could not solve the problem.

Mahdiyeh avatar Jun 24 '22 07:06 Mahdiyeh