My way using HTML pattern.
- Allows only number.
- Shows number pad on mobile.
- Prevent pasting of
non-numbers.
- Show error message if less than 1
code sand box
add pattern props to inputProps to allow only 0 to 9.
pattern: "[0-9]*"
use e.target.validity.valid to check if pattern is valid (only allow 0-9)
const [ value, setValue ] = useState(1)
const onChange = (e) => {
console.log('e.validity', e.target.validity.valid);
if (e.target.validity.valid || e.target.value === '') setValue(e.target.value)
}
add type="tel" (this will show number pad on mobile)
<TextField
variant="standard"
name="price"
value={value}
fullWidth
onChange={onChange}
type="tel"
error={value < 1}
helperText={ value < 1 ? 'Min. 1' : '' }
inputProps={{
pattern: "[0-9]*",
}}
/>