Automatically takes a space after 4 letters in the text input field in

If I entered the text in the text input field, then it automatically takes a space after 4 digits.

Here is my code for the text input field:

handleCardNumber = (text) => {
    this.setState({ cardNumber: text })
}

<TextInput
    ref="first"
    underlineColorAndroid="transparent"
    autoCapitalize="none"
    style={styles.cardNumberTextInput}
    placeholder="1234 1234 1234 1234"
    placeholderTextColor="grey"
    returnKeyType='next'
    keyboardType = {'numeric'}
    onChangeText={this.handleCardNumber}
    onSubmitEditing={(event)=>{
    this.refs.second.focus();
}}

Here is my screenshot:

enter image description here

+4
source share
1 answer

Replace the code below:

handleCardNumber = (text) => {
  let formattedText = text.split(' ').join('');
  if (formattedText.length > 0) {
    formattedText = formattedText.match(new RegExp('.{1,4}', 'g')).join(' ');
  }
  this.setState({ cardNumber: formattedText });
  return formattedText;
}

Add this line to your input code to show the change status value:

value={this.state.cardNumber}

JS Demo: (enter more than 4 digits)

handleCardNumber = (text) => {
      let formattedText = text.split(' ').join('');
      if (formattedText.length > 0) {
        formattedText = formattedText.match(new RegExp('.{1,4}', 'g')).join(' ');
      }
      //this.setState({ cardNumber: text });
      console.log(formattedText)
      return formattedText;
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" onchange="handleCardNumber(this.value)" >
Run code
0
source

Source: https://habr.com/ru/post/1685865/


All Articles