1

We are using KeyboardDatePicker from @material-ui/pickers with date-fns, on a website designed with material-ui. Everything works with the KeyboardDatePicker, except we wanted to prevent form submission if the date is invalid. After some trial and error, we have implemented this with KeyboardDatePicker's onError property:

<MuiPickersUtilsProvider utils={DateFnsUtils} locale={elLocale}>
  <KeyboardDatePicker
      disableToolbar
      variant="inline"
      format="dd/MM/yyyy"
      margin="normal"
      id="labDate"
      label="Ημερομηνία διεξαγωγής"
      value={labDate}
      onChange={handleDateChange}
      invalidDateMessage='Μη έγκυρη ημερομηνία'
      onError={(err, value) => setLabDateError(err, value)}
      />
 </MuiPickersUtilsProvider>

  const setLabDateError = (err, value) => {
    if (value===null || err===''){
      setDateErr('')
    } else {
      setDateErr(err)
    }
  }

Then on submission, we check the dateErr state variable and if it is not empty (there is a date error), we don't submit. The code works fine, but I've noticed when doing a console.log of err and value in setLabDateError(), that the function runs every time I change a field in the form. Even if it is a field other that labDate. As I said the code works fine, but I'm wondering why this is happening and if it is something that could cause problems in the future. I've tried to find more details about onError and how/when it gets called, but I haven't managed to find anything.

Olivier Tassinari
  • 8,238
  • 4
  • 23
  • 23

0 Answers0