Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MUI TextField not accepting pattern

I want to make Material UI TextField to only accept number values, in the MUI documentation the solution is as following:

<TextField inputProps={{ inputMode: 'numeric', pattern: '[0-9]*' }} />

However this is for the version 5 of MUI, and in my case I'm using the version 4, so I tried as following:

<TextField
      InputProps={{
        inputProps: {
          inputMode: "numeric",
          pattern: "[0-9]*"
        }
      }}
    />

But for some reason, this is not working, and I can still type values other than numbers in the input.

Using input="number" is not an option, as I don't want to keep the 0 when the input is empty, neither I want the stepper to be visible.

Full example is in this sandbox: https://codesandbox.io/s/mui4-forked-0j98er?file=/src/App.js:136-408

How can I solve this ?

like image 957
Renaud is Not Bill Gates Avatar asked Sep 10 '25 12:09

Renaud is Not Bill Gates


1 Answers

You can use controlled input and clean value from non-numeric characters

export default function MyComponent() {
  const [inputValue, setInputValue] = useState("");

  function onChange(e) {
    setInputValue(e.target.value.replace(/\D/g, ""));
  }

  return (
    <TextField
      label="number input"
      variant="outlined"
      color="secondary"
      fullWidth
      value={inputValue}
      onChange={onChange}
      inputProps={{
        maxLength: 5
      }}

    />
  );
}

I was inspired by @Dmitriif's answer because it uses less code. But I tweaked it a bit. live demo However, the min: 0 doesn't work

export default function IconButtons() {
  return (
    <TextField
      label="number input"
      variant="outlined"
      color="secondary"
      fullWidth
      inputProps={{
        type: "text",
        inputMode: "numeric",
        pattern: "d*",
        min: 0,
        maxLength: 5
      }}
    />
  );
}
like image 82
Edshav Avatar answered Sep 13 '25 06:09

Edshav