I have the following input field, I would like it to accept only positive integers, without giving the possibility to insert the characters - + , .
.
<TextField
fullWidth
type="number"
placeholder={'[1-100]'}
id="simple-start-adornmhent"
onChange={this.handleChangeField('amount')}
InputProps={{ inputProps: { min: 1 } }}
/>
Can you give me some advice?
Basic idea is: Use controlled component (use value and onChange property of input field), and inside onChange handle check whether the entered value is proper number or not. Update the state only when entered value is a valid number.
The MUI TextField can display a default value on render by using the defaultValue prop. This is useful if you don't need to externally get or set the TextField value, or if you are using a form. A form will automatically extract a TextField child components value on submit of the form.
In the onChange method you can create your own rule to deal with the data.
In this case below, if the input value is less then zero, then I set the value to zero.
This solved my problem. You can improve the rule as you need.
<TextField
type={"number"}
onChange={(event) =>
event.target.value < 0
? (event.target.value = 0)
: event.target.value
}
/>
How about setting type to "text" and manually control the input? try this:
<TextField
value={this.state.value}
onChange={(e) => {
let input = e.target.value ;
if( !input || ( input[input.length-1].match('[0-9]') && input[0].match('[1-9]')) )
this.setState({value:input})
}}
type="text"
placeholder={'[1-100]'}
/>
with this code we only allow the first character to be [1-9] and the following charaters to be [0-9]. we also allow the TextField to be empty
Try This
<TextField type="number"
label="Short stop treshold"
InputProps={{
inputProps: { min: 0 }
}}
value={10}
onChange={handleShortStopChange} />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With