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 ?
CodePudding user response:
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
}}
/>
);
}
CodePudding user response:
TextField
in mui v4 also has inputProps
property which can help you to apply desired attributes to the input
element. However, you will need to set another property type="number"
to make the component work correctly in your case:
<TextField
label="number input"
variant="outlined"
color="secondary"
fullWidth
type="number"
inputProps={{
min: 0,
maxLength: 5,
inputMode: "numeric",
pattern: "[0-9]*"
}}
/>