Showing errors for badly formatted date and time fields

I am currently experiencing odd behavior with date, date-time, and time fields, specifically with the React and MUI integration.

The odd behavior can be reproduced in any of the examples, such as the basic example:

  1. Type any string in the Birth Date field.
  2. Note that there is no validation error, although the format is date.
  3. Click on the data tab and note that birthDate is missing.

I believe the cause of this behavior is due to the createOnChangeHandler util. Specifically, this line which sets the field’s data to undefined when the date string is invalid:

handleChange(path, result === 'Invalid Date' ? undefined : result);

Is there a recommended way to handle date fields, and prevent users from inputting badly formatted dates? I want to avoid creating a custom renderer, but am happy to contribute to the @jsonforms/material-renderers package if necessary.

1 Like

Hi @sunnysingh,

You’re right, the current behavior is not intuitive at all.

I would like to suggest to change the behavior to just write-through invalid inputs and therefore provoking validation errors. We just need to make sure that the renderer does not crash with these invalid inputs.

A contribution would be welcomed :wink:

Appreciate the reply @sdirix, I’m glad to hear that you agree. I’ll see if I can contribute a fix soon, assuming that we’re okay with this being a breaking change considering this changes previous handleChange behavior.

I did try this as a temporary and very hacky workaround in a custom renderer:

import * as React from 'react';
import { ControlProps, rankWith, isTimeControl } from '@jsonforms/core';
import { withJsonFormsControlProps } from '@jsonforms/react';
import { Unwrapped } from '@jsonforms/material-renderers';

export const Renderer = withJsonFormsControlProps((props: ControlProps) => {
  return (
    <Unwrapped.MaterialTimeControl
      {...props}
      handleChange={(key, value) => {
        const inputElement = document.getElementById(`${props.id}-input`) as HTMLInputElement;

        // Propagate invalid date values to show user errors.
        if (value === undefined && inputElement?.value) {
          props.handleChange(key, inputElement.value);
          return;
        }

        props.handleChange(key, value);
      }}
    />
  );
});

export const tester = rankWith(5, isTimeControl);

…which didn’t break anything, but also not the React way of doing things so I prefer to avoid it.

Hi @sunnysingh,

I agree, accessing the DOM directly is certainly not that nice, however for a temporary workaround this should be fine. Fixing this in JSON Forms is certainly the preferred way of handling this.

1 Like

Created the following PR which passes through keyboardInputValue when the date format result is Invalid Date: Pass through original values for invalid dates by sunnysingh · Pull Request #1949 · eclipsesource/jsonforms · GitHub

1 Like

Thank you! That’s awesome!