I have a question about updating UI in real-time (when typing). Is this the right approach?
I have this code:
Regex Method:
determineCardBrand(number) {
var re = new RegExp("^4");
var reMC = new RegExp(
"/^(5[1-5][0-9]{14}|2(22[1-9][0-9]{12}|2[3-9][0-9]{13}|[3-6][0-9]{14}|7[0-1][0-9]{13}|720[0-9]{12}))$/",
);
if (number.match(re) != null) {
return "Visa";
} else if (number.match(reMC) != null) {
return "MasterCard";
} else {
return "";
}
}
View code snippet:
<View style={{ flexDirection: "row" }}>
<CardLogo
style={styles.cardLogo}
cardType={
cardNumber === ""
? "Inactive"
: this.determineCardBrand(cardNumber)
}
/>
<TextInputMask
underlineColorAndroid={"transparent"}
type={"credit-card"}
maxLength={19}
style={[Styles.paymentCardInput, { flexGrow: 1 }]}
onChangeText={cardNumber => {
this.setState({ cardNumber });
this.determineCardBrand(cardNumber);
}}
value={cardNumber}
returnKeyType="done"
/>
</View>
Where I want to determine if what card number I type is associated to what CC brand (e.g. visa, mastercard, etc..). So as I type a card number, I want the card logo to change based on what I type for the number. CardLogo component has a switch statement that determines if type name is passed is e.g. Visa, then show the Visa logo.
Is this the right approach?
Normally, you can find out from the first four digits (I think) but sometimes just the first one e.g. like the visa card.. always starts with four. I tested out the above but for some reason, it only works for Visa or unknown CC, not Mastercard. I'm not sure if it's because of the Regex or the way I have the code setup above.