Reputation: 6347
I'm trying to create an input element that only allows positive numbers, including decimal values. It can't have leading zeros, it can't allow users to copy/paste an invalid value (eg. -14.5) in the field.
What I have so far:
<input type="number" onChange={this.handleChange} value={this.state.value}/>
private handleChange= (e) => {
let amount = parseFloat(e.target.value);
if (isNaN(amount) || amount < 0) {
amount = 0;
}
this.setState({value: amount});
}
This works except it always keeps a leading zero. How can I fix it?
Upvotes: 1
Views: 3094
Reputation: 1410
Just don't perform the set state if its NaN
or negative
.
Then, when you intend to insert anything wrong, it just won't change anything.
Upvotes: 0
Reputation: 5586
The following will check the presence of zero at first position.
e.target.value.indexOf('0') === 0
Note:
keyup
event is preferred overonclick
event for inputs.
App.jsx
import React from 'react';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
value: ''
}
this.handleChange = this.handleChange.bind(this);
}
render() {
return (
<div>
<input type="number" onChange={this.handleChange} value={this.state.value} />
</div>
)
}
handleChange(e) {
let amount = parseFloat(e.target.value);
if (isNaN(amount) || amount < 0 || e.target.value[0] === '0') {
amount = '';
}
this.setState({value: amount});
}
}
export default App;
Upvotes: 3