skip to Main Content

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

2

Answers


  1. InputProps properties are handled in Material-UI’s component.
    Users can still enter values outside the specified range

    You can try something like that:

      const YourComponent = () => {
      const [quantity, setQuantity] = useState(0);
    
      const handleChange = (event) => {
        const value = event.target.value;
        if (value >= 0 && value <= 100) {
          setQuantity(value);
        }
      };
    
      return (
        <TextField
          className="input-quantity form-input"
          value={quantity}
          name="quantity"
          type="number"
          InputProps={{
            inputProps: {
              min: 0,
              max: 100,
            },
          }}
          onChange={handleChange}
        />
      );
    };
    
    Login or Signup to reply.
  2. <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";
        }
      }}
    />
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search