Mr Ish
Mr Ish

Reputation: 13

Clear date field when user entered invalid date in MUI Date picker React.js

When a user enters an invalid date, I want to clear their input. How can I achieve this?

Clear date field when user enters only month

I tried the below sample, but I don't see it clearing.

import * as React from 'react';
import { DemoContainer } from '@mui/x-date-pickers/internals/demo';
import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs';
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
import { DatePicker } from '@mui/x-date-pickers/DatePicker';
import dayjs from "dayjs";

export default function BasicDatePicker() {
  const [inputDate, setInputDate] = React.useState<string | null>(null);
  return (
    <LocalizationProvider dateAdapter={AdapterDayjs}>
      <DemoContainer components={['DatePicker']}>
        <DatePicker label="Basic date picker" value={inputDate} 
        onChange={(newValue) => {
          const parsedDate = dayjs(newValue);
          if (parsedDate.isValid()) {
             const formattedDate = parsedDate.format('YYYY-MM-DD');
             setInputDate(formattedDate);
          } else {
            setInputDate(null);
          }
       }}
        />
      </DemoContainer>
    </LocalizationProvider>
  );
}

I also tried clearing it in an onBlur function. This one cleared the value of date picker, but when I tried to enter a new value I saw the old value still shown.

import * as React from 'react';
import { DemoContainer } from '@mui/x-date-pickers/internals/demo';
import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs';
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
import { DatePicker } from '@mui/x-date-pickers/DatePicker';
import dayjs from "dayjs";

export default function BasicDatePicker() {
  const [inputDate, setInputDate] = React.useState<string | null>(null);
  
  const debounce = (func: (...args: any[]) => void, wait: number) => {
    let timeout: NodeJS.Timeout | null;
    return function (this: any, ...args: any[]) {
       const context = this;
       const later = function () {
          timeout = null;
          func.apply(context, args);
       };
       clearTimeout(timeout as NodeJS.Timeout);
       timeout = setTimeout(later, wait);
    };
 };

 const onBlurDebounced = debounce((event: React.FocusEvent<HTMLInputElement | HTMLDivElement>) => {
    const userInput = (event.target as HTMLInputElement).value;
    if (userInput !== "" && userInput !== undefined && userInput !== null) {
       const parsedDate = dayjs(userInput, 'MM/DD/YYYY');
       if (!parsedDate.isValid()) {
          (event.target as HTMLInputElement).value = '';
       }
    }
 }, 250);

  return (
    <LocalizationProvider dateAdapter={AdapterDayjs}>
      <DemoContainer components={['DatePicker']}>
        <DatePicker label="Basic date picker" value={inputDate} 
        onChange={(newValue) => {
          const parsedDate = dayjs(newValue);
          if (parsedDate.isValid()) {
             const formattedDate = parsedDate.format('YYYY-MM-DD');
             setInputDate(formattedDate);
          } else {
            setInputDate(null);
          }
       }}
       slotProps={{
        textField: {
           fullWidth: true,
           size: 'small',
           onBlur: onBlurDebounced,
           value: inputDate ? dayjs(inputDate) : null
        }
     }}
        />
      </DemoContainer>
    </LocalizationProvider>
  );
}

Upvotes: 0

Views: 112

Answers (0)

Related Questions