2

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

1 Answer 1

1

I would do it like this: add onKeyPress={this.handleKeyPress} to your TextInput, then:


handleKeyPress(evt) {
    evt = (evt) ? evt : window.event;
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode > 31 && ((charCode < 48 || charCode > 57) || charCode != 188)) {
        return false;
    }
    if (this.value.match(/,.*,/g) return false;

    return true;
}

Sign up to request clarification or add additional context in comments.

6 Comments

What do you mean? Your input element is not accepting such values?
I added sandbox above, could you check it?
You have to remove the hardcoded value={this.state.sum} at <input/>, that's causing the lock
if I remove it how then it will validate the input? that is I entered 123,55,8899 ... I need a second comma not to be allowed to enter.
thanks for your efforts. I've already solved it and I've posted it in my question update. Moreover the solution is for React Native, not for PC keyboard.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.