I need to validate number with two decimal in TextInput (React Native) to prevent the insertion of the second comma.
Right now I can enter 123,12,23 and it breaks the app.
export default class Bottom extends Component {
constructor(props){
super(props)
this.state = {
sum:'',
}
this.handleInputChange = this.handleInputChange.bind(this);
}
handleInputChange(value) {
// validation of the value
this.setState({sum: value});
}
render () {
return (
<View>
<TextInput
style={styles.input}
keyboardType ="decimal-pad"
autoCorrect={false}
placeholder='add'
onChangeText={ this.handleInputChange }
value={this.state.sum}
/>
</View>
);
}
I tried to use indexOf but it deletes the first comma, not the second
if (value.indexOf(',') === -1) {
this.setState({sum: value});
Any suggestions or link to right answers?
Update
I've resolved it:
handleInputChange(value) {
let lastValid = this.state.sum;
//var validNumber = new RegExp(/^\d*\.?\d*$/); // for dot
var validNumber = new RegExp(/^\d*\,?\d*$/); // for comma
if (validNumber.test(value)) {
lastValid = value;
} else {
value = this.state.sum;
}
this.setState({ sum: lastValid });
}
Sandbox updated as well
Sandbox:https://codesandbox.io/s/unruffled-blackwell-208p6?file=/src/App.js