reactjstypescriptmaterial-ui

Material UI Textfield how to make it accept specific format?? (hh:mm:ss)


I'm trying to make my material ui textfield to accept the format of hh:mm:ss. What I mean is being able to change the numbers on hh mm and ss, while : are automatic. Any tips will be appreciated.


Solution

  • Use an onchange and then don't allow non numerics and insert the colons:

    import{ useState } from "react";
    import TextField from "@mui/material/TextField";
    
    function App() {
      // TimeInput component defined inside App
      const TimeInput = () => {
        const [time, setTime] = useState("");
    
        const handleTimeChange = (e) => {
          let value = e.target.value;
    
          // Remove any non-numeric characters except colons
          value = value.replace(/[^0-9:]/g, "");
    
          // Auto-insert colons
          if (value.length === 2 || value.length === 5) {
            value += value.endsWith(":") ? "" : ":";
          }
    
          // Limit length to 8 characters (hh:mm:ss)
          value = value.slice(0, 8);
    
          setTime(value);
        };
    
        return (
          <TextField
            label="Time (hh:mm:ss)"
            value={time}
            onChange={handleTimeChange}
            placeholder="00:00:00"
          />
        );
      };
    
      return (
        <div className="App">
          <h1>Time Input Example</h1>
          <TimeInput />
        </div>
      );
    }
    
    export default App;
    

    Here it is in code sandbox