Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
301 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...