Harika
Harika

Reputation: 1131

Automatically takes a space after 4 letters in text input field in react-native

If i entered text in text-input field then automatically it takes a space after 4 digits.

Here is my code for 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

Upvotes: 4

Views: 7023

Answers (1)

Jigar Shah
Jigar Shah

Reputation: 6223

Replace your code with 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 in your input code to show changes state 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)" >

Upvotes: 4

Related Questions