简体   繁体   English

条纹元素:如何验证卡片元素不是空白客户端?

[英]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: Stripe 建议使用change事件对card元素进行客户端验证:

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.我总是可以尝试使用confirmCardPayment提交付款,但这效率低下——这种验证应该可以在客户端进行。

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.我可以通过将付款表单默认为错误 state 来解决此问题,然后在用户第一次更改卡时解决(或不解决)该错误。 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.但是,这并不方便,因为它需要我将应用程序代码中的“您的卡号不完整”错误消息国际化,而不是依赖 Stripe。

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: Stripe.js 根据元素的 state 将几个类应用于每个 Stripe 元素的容器:

  • StripeElement--complete
  • StripeElement--empty
  • StripeElement--focus
  • StripeElement--invalid
  • StripeElement--webkit-autofill (Chrome and Safari only) StripeElement--webkit-autofill autofill(仅限 Chrome 和 Safari)

You can read more about these classes, including how to customize them, in Stripe's documentation .您可以在Stripe 的文档中阅读有关这些类的更多信息,包括如何自定义它们。

It sounds like checking for the StripeElement--empty class might suffice for your use case.听起来检查StripeElement--empty class 可能足以满足您的用例。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM