MS-Office React-Fabric UI - How to show required error message on date picker when a form is SUBMITTING?

3.5k Views Asked by At

I want to show an error message on the date picker when a form is submitting, but I found no way to do so.

isRequiredErrorMessage works only when the field loses the focus with empty value.

However, if users never focus on the date picker field, then I have no way to set message to the error label.

I wish that the DatePicker can have errorMessage, such that I that do something like

render() {
  return (
    <DatePicker
      label="Pick up date"
      isRequired={true}
      minDate={moment().toDate()}
      onSelectDate={(date) => {this.setState({pickUpDate: date})}}
      strings={DayPickerStrings}
      errorMessage={this.state.pickUpDateErrorMessage}
    />
  );
}

onSubmitForm() {
  if (isNaN(this.state.pickUpDate)) {
    this.setState({
      pickUpDateErrorMessage: "Can't be empty"
    })
  }
}

Please suggest how to validate datePicker component on form submitting.

2

There are 2 best solutions below

1
On

It looks like you are using TypeScript. Try extending the DatePicker class with your own class that has a errorMessage property.

export class MyDatePicker extends DatePicker {
    public constructor(props: {}) {
        super(props);
    }

    errorMessage: string = '';
}

Then call your own MyDatePicker component in place of the original DatePicker component.

0
On

I had similar need to show error message on DatePicker and wanted similar errorMessage API as for other input components in office-fabric-ui-react. I finally found out Datepicker as textfield property since essentially it uses TextField and so you can pass in ITextFieldProps to it.

Sample solution:-

<DatePicker
name="someDate"
id="someDate"
isRequired={true}
textField={{ errorMessage: "someErrorMessage" }}
/>

Below is docs link:-

https://learn.microsoft.com/en-us/javascript/api/office-ui-fabric-react/idatepickerprops?view=office-ui-fabric-react-latest#textfield