React - trying to validate textfield input - "event.target.setValue is not a function"

I'm trying to implement a text field that only allows numbers from 0 to 99. If the user enters a number that is negative or larger than 99, I want the textfield to reset to 0. Here is my code:

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

export default function TestForm() {
  return (
    <React.Fragment>
 <TextField
            required
            id="field1"
            name="field1"
            label="How Many"
            fullWidth
            type="number"
            defaultValue="0"
            variant="standard"
            onChange={function (event) {
              if (event.target.value < 0 || event.target.value > 99) {
                event.target.setValue("0");
              }
            }}
          />
 </React.Fragment>
  );
}

When I run this in CodeSandbox I get the following error:

event.target.setValue is not a function

Any advice would be appreciated.


Solution 1:

I'm not familiar with a setValue property on an input element. But the react way to do it is to hold the value in local state using useState and make the TextField a controlled element by adding the value prop.

export default function TestForm() {
    const [value, setValue] = React.useState(0)
    return (
        <TextField
            value={value}
            onChange={function (event) {
                if (event.target.value < 0 || event.target.value > 99) {
                    setValue("0");
                } else {
                    setValue(event.target.value)
                }
            }}
        />
    );
}

Solution 2:

In react you need to store the input value in state

Try this code it's help you

import React, { useState } from "react"

function App() {
  const [state, setState] = useState('');

  const handleChange = (event) => {
    if (event.target.value < 0 || event.target.value > 99) {
      setState(event.target.value);
    }
  }
  return (
    <>
      <React.Fragment>
        <TextField
          required
          id="field1"
          name="field1"
          label="How Many"
          fullWidth
          type="number"
          defaultValue="0"
          variant="standard"
          value={state}
          onChange={(e) => handleChange(e)}
        />
      </React.Fragment>
    </>
  );
}
export default App;