Reputation: 6003
Here I have one input field this input field is number type So i make validation on this input field of number type see in code(it allows only numbers) it works perfectly but after typing some integers and when I go to make empty input field it is not removes last one character in input field how to remove that also ?
<Input
name='monthlyPrice'
type='number'
value={this.state.monthlyPrice}
onChange={this.onInputChangeValue}
/>
onInputChangeValue(e){
if(e.target.value.match(/^\d+(?:\.\d+)?$/)) {
this.setState({ [e.target.name]: e.target.value })
}
}
Upvotes: 2
Views: 5998
Reputation: 1
you can use useRef for fetching values and onChange event for triggering any function if you need
Upvotes: 0
Reputation: 79
I had the same issue and what worked for me is to simply use defaultValue
instead of value
in your
Upvotes: -1
Reputation: 1273
I guess you can reset the state before setting it to the new value.
onInputChangeValue(e){
this.setState({[e.target.name]: "" }, () => {
if(e.target.value.match(/^\d+(?:\.\d+)?$/)) {
this.setState({ [e.target.name]: e.target.value })
}
})
}
Upvotes: -2
Reputation: 1397
You need to add your ||
back in from your previous question:
<Input
name='monthlyPrice'
type='number'
value={this.state.monthlyPrice}
onChange={this.onInputChangeValue}
/>
onInputChangeValue(e){
if(e.target.value == "" || e.target.value.match(/^[1-9]\d*\.?\d*$/)) {
this.setState({ [e.target.name]: e.target.value })
}
}
Note: This would still require you to check before the form is submitted, as this would allow them to leave the field ending in a .
character. You could also do this in an onBlur
if you wanted to. The regex to test for this would be ^[1-9]\d*(?:\.\d+)?$
Note 2: This regex is based on OP's first question which required the first digit to be 1-9
Upvotes: 5