Search code examples
reactjsmaterial-uifrontend

MUI TextField number type min max not working


Material UI version: "@mui/material": "^5.15.15",

Here's the snippet code

<TextField
 className="input-quantity form-input"
 defaultValue={0}
 name={"quantity"}
 type="number"
 InputProps={{
    inputProps: {
      min: 0,
      max: 100,
    },
 }}
 onChange={(event: any) =>
    handleChange(e)
 }
/>

the input still can pass over 100, even to thousand value.

this happened to text type too as the inputProps used maxLength


Solution

  • <TextField
      className="input-quantity form-input"
      defaultValue={0}
      name="quantity"
      type="number"
      InputProps={{
        inputProps: {
          min: 0,
          max: 100,
        },
      }}
      onChange={(event: any) => handleChange(event)}
      onInput={(e) => {
        const numericValue = parseFloat(e.target.value);
    
        // Check if the numeric value exceeds the max value (100)
        if (!isNaN(numericValue) && numericValue > 100) {
          e.target.value = "100";
        }
    
        // Check if the numeric value is below the min value (0)
        if (!isNaN(numericValue) && numericValue < 0) {
          e.target.value = "0";
        }
      }}
    />