how to allow only numbers in mui textfield?

Hi Friends 👋,

Welcome To aGuideHub! ❤️

To allow only numbers in mui textfield, you can set textfield type as number or you can use /^[0-9\b]+$/ numeric regex in your material ui textfield onchange attribute.

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

Allow only numbers in mui text field using type attribute

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

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.

codesandbox

Allow only numbers in mui text field using regex

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.

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();

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

  return (
    <Box component="form">
      <TextField
        type="text"
        id="outlined-basic"
        label="Outlined"
        variant="outlined"
        onChange={(e) => handleChange(e)}
        value={num}
      />
    </Box>
  );
}

In the above example, we have used regex in Mui textfield to force users to enter only numbers, you can use this regex for validation purposes also.

codesandbox

All the best 👍

Premium Content

You can get all the below premium content directly in your mail when you subscribe us

Books

Interview Questions

Soon You will get CSS, JavaScript, React Js, and TypeScript So Subscribe to it.

Portfolio Template

View | Get Source Code

Cheat Sheets

Cheat Sheets Books are basically Important useful notes which we use in our day-to-day life.

Related Posts