Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
311 views
in Technique[技术] by (71.8m points)

javascript - Stripe elements: how can I validate a card element is not blank client-side?

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.

question from:https://stackoverflow.com/questions/65862556/stripe-elements-how-can-i-validate-a-card-element-is-not-blank-client-side

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...