how to allow only numbers in mui textfield?

Hi Friends 👋,

Welcome To aGuideHub! ❤️

Allow only numbers in mui text field

To allow only numbers in mui textfield, set mui textfield as a type="number"it allows the user to enter only numbers.

<TextField
  type="number"
  id="outlined-basic"
  label="Outlined"
  variant="outlined"
  onChange={(e) => setNum(e.target.value)}
  value={num}
/>

If type="number" method not work for you because some cases we have to stick on type text so in this case you can also use /^[0-9\b]+$/ in your onChange function like this.

const handleChange = (e) => {
  const regex = /^[0-9\b]+$/;
  if (e.target.value == "" || regex.test(e.target.value)) {
    setNum(e.target.value);
  }
};

<TextField
  type="text"
  id="outlined-basic"
  label="Outlined"
  variant="outlined"
  onChange={(e) => handleChange(e)}
  defaultValue={num}
  value={num}
  inputProps={{ maxLength: 12 }}
/>;

Today, I am going to show you. how to allow only numbers in mui textfield.

Installation

Emotion library is required to create react components that have styles attached to them.

npm install @mui/material @emotion/react @emotion/styled

MUI material textfield type number example

To create input type number in mui textfield, pass type props with number it will work the same as the input type number and it only allows the number to enter in text field.

App.js

import * as React from "react";
import Box from "@mui/material/Box";
import TextField from "@mui/material/TextField";

export default function BasicTextFields() {
  const [num, setNum] = React.useState();
  return (
    <Box component="form">
      <TextField
        type="number"
        id="outlined-basic"
        label="Outlined"
        variant="outlined"
        onChange={(e) => setNum(e.target.value)}
        value={num}
      />
    </Box>
  );
}

In the above code example, I have used the @mui/material TextField component and used it as a number TextField.

Check the output of the above code example.

All the best 👍

Follow me on Twitter