I want to restrict input upto 2 places after decimal.
class MyComponent extends React.Component {
constructor(props) {
super(props)
this.state = {
stateValue: "",
}
this.handleChange = this.handleChange.bind(this)
}
handleChange(event){
let value = event.target.value
let regex = new RegExp("^[0-9]*[.]{0,1}[0-9]{0,2}$")
if(!regex.test(value)){
console.log("wrong Input")
return
} else {
this.setState((prevState) => ({
...prevState,
stateValue: value,
}))
}
}
render(return (<div> <input type="number" onChange={handleChange} /> </div>)
}
}
the above code snippet works fine except the case when i'm using 0 from 3rd position after the decimal and continue pressing 0. For example
- pressed 12.231 --> not proceeding after 2 decimals i.e. 12.23 is visible on screen.
- pressed 12.23000000 -->12.23000000 appearing on screen, even though i'm getting "wrong Input" in console as printed by the console.log for all the input after 2 places of decimal