Stripe recommends using the change
event for client side validation of the card
element:
cardElement.on('change', function(event) {
if (event.complete) {
// enable payment button
} else if (event.error) {
// show validation to customer
}
});
However this approach makes it impossible to determine a card element is invalid if the user never edits / changes it. I can always try to submit the payment with confirmCardPayment
but that is inefficient—this validation should be possible client-side.
I can work around this by having the payment form default to an error state that is then resolved (or not) the first time the user changes the card. However this is not convenient as it would require me to internationalize the "Your card number is incomplete" error message in my application code versus relying on Stripe to this.
Ideally I would be able to either synchronously check the card element for an error or at least synchronously trigger the change event but neither of these seem possible.
Stripe.js applies several classes to every Stripe Element's container based on the state of the Element:
StripeElement--complete
StripeElement--empty
StripeElement--focus
StripeElement--invalid
StripeElement--webkit-autofill
(Chrome and Safari only) You can read more about these classes, including how to customize them, in Stripe's documentation .
It sounds like checking for the StripeElement--empty
class might suffice for your use case. You can do something like this:
const cardElementContainer = document.querySelector('#card-element');
let cardElementEmpty = cardElementContainer.classList.contains('StripeElement--empty');
// Do things based on cardElementEmpty being true or false
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.