skip to Main Content

I’ve been trying to create a date picker field that can allow for certain invalid date ranges i.e. 00 if the DD or MM for a date of birth is of an unknown value. The base UI components that I am using are MUI’s DatePicker and MUI’s FilledInput / TextField. For instance, a person with a birth date of March 1943 should be able to input their DOB as 00 / 03 / 1943 on the front end.

So far, as far as I understand and read, this can’t be done with input fields of ‘type = "date"’ as 00 would be autocorrected to 01.

As a continuation to the above question, I have used a standard text field instead with masking, such as react-imask library and it works (sort of haphazardly). A key feature that I am still missing if I were to use a text field is that my text input is not split neatly into each date block (Day,Month,or Year) like the MUI example attached
enter image description here

My questions are:

  1. Is there a way to build such a custom date picker using date inputs?
  2. If not, would using a text field be a suitable solution to the problem?
  3. How can I get the described behavior to get my blocks of text to correspond to each date block?

2

Answers


  1. You can use a regular text field and add a regex pattern to enforce a certain format.

    import React, { useState } from 'react';
    
    const DateInput = () => {
    const [date, setDate] = useState('');
    
    const handleDateChange = (e) => {
        const inputDate = e.target.value;
        const formattedDate = inputDate.replace(
        /^(d{0,2})/(d{0,2})/(d{0,4})$/,
        (match, p1, p2, p3) => {
            const day = p1.padStart(2, '0');
            const month = p2.padStart(2, '0');
            const year = p3.padEnd(4, '0');
            return `${day}/${month}/${year}`;
        }
        );
    
        setDate(formattedDate);
    };
    
    const handleBlur = () => {
        // Validate date
        // ...
    };
    
    return (
        <input
        type="date"
        pattern="d{0,2}/d{0,2}/d{0,4}"
        inputMode="numeric"
        placeholder="DD/MM/YYYY"
        value={date}
        onChange={handleDateChange}
        onBlur={handleBlur}
        />
    );
    };
    
    export default DateInput;
    
    Login or Signup to reply.
  2. For maximum re-use, I suggest you offer two input fields, one for birthdays with date and one without:

    <TextField label="Birthday" type="date"/>
    <TextField label="Month of birth" type="month"/>
    

    This MUI code looks different, but works like the HTML code below:

    <div>
    Birthday <input type="date"/><br>
    Month of birth <input type="month"/>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search