0

I can limit the quantity of input if the user use the built in arrow icon inside the textfield. But when the user type it, it's not working

User use the keyboard

<TextField variant="outlined" label="Quantity" 
                onChange={(e) => setItemName({...itemName, quantity: e.target.value})} 
                type="number"
                fullWidth name="quantity"  InputProps={{ inputProps: { min: 0, max: 10, maxLength: 2}}}
                pattern="^-?[0-9]\d*\.?\d*$"
                />
Zurcemozz
  • 183
  • 1
  • 9
  • https://stackoverflow.com/questions/45939909/put-length-constraint-in-a-textfield-in-react-js does this solves your issue? – PakDragoon Nov 29 '22 at 06:51

2 Answers2

1

You can do:

onInput={(e) => {e.target.value > 10 ? e.target.value = 10 : e.target.value}}
George Chond
  • 977
  • 1
  • 3
  • 12
-1

You can cater that in your onChange handler. Check if the input value is greater than max, assign the max to your input value

<TextField
  variant="outlined"
  label="Quantity" 
  onChange={(e) => {
     const { target: { value, max } } = e;
     let inputValue = value;
     if (inputValue > max) inputValue = max;
     setItemName({ ...itemName, quantity: inputValue })
  }
  type="number"
  fullWidth
  name="quantity"
  InputProps={{ inputProps: { min: 0, max: 10, maxLength: 2}}}   
  pattern="^-?[0-9]\d*\.?\d*$"
/>
  • OP wants to stop from typing text above 10. `onInput` event occurs immediately after the value of an element has changed, while `onChange` occurs when the element loses focus, after the content has been changed. So this may work for the `setItemName` part, but it won't stop the user from typing a value>10. – George Chond Nov 29 '22 at 07:06