React Native: How to format payment in mm/yy and spaced 16-digit card number in Javascript?
css, javascript, react-native, reactjs
Solution
I'll add the handling card number, since it was part of the original question:
_handlingCardNumber(number) {
this.setState({
cardNumber: number.replace(/\s?/g, '').replace(/(\d{4})/g, '$1 ').trim()
});
}
where:
<TextInput
onChangeText={(text) => this._handlingCardNumber(text)}
placeholder='0000 0000 0000 0000'
value={this.state.cardNumber}
/>
Problem
In React Native, I have two `<TextInput/>`, one which receives MM/YY and the other 16-digit card number. In the first input for MM/YY, I have: ``` <TextInput onChangeText={this._handlingCardExpiry.bind(this)} placeholder='MM/YY' value={cardExpiry} /> ``` And for the 16-digit card number: ``` <TextInput onChangeText={this._handlingCardNumber.bind(this)} placeholder='0000 0000 0000 0000' value={cardNumber} /> ``` For the expiry, I attempted to split them up and store in the value property as `${cardMonth}/${cardYear}`, but the text would not even rather, and adding space after every 4 digits to the card number input cause texts to not appear in the input. What would be the right approach to handling the following with the < TextInput />'s onChangeText and value properties: - When a user starts typing in `<TextInput/>`, show a `/` in the middle and inputting first two digits would appear before the `/` and next two after. - When a user starts typing in 16-digit card number, automatically place space after every 4 digits entered in. Thank you in advance and will vote up/accept the answer.