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

Tom*_*man 10 javascript validation stripe-payments

Stripe 建议使用该change事件对card元素进行客户端验证:

\n
cardElement.on('change', function(event) {\n  if (event.complete) {\n    // enable payment button\n  } else if (event.error) {\n    // show validation to customer\n  }\n});\n
Run Code Online (Sandbox Code Playgroud)\n

然而,如果用户从未编辑/更改卡片元素,这种方法就无法确定它是无效的。我总是可以尝试提交付款confirmCardPayment,但效率低下\xe2\x80\x94此验证应该可以在客户端进行。

\n

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

\n

理想情况下,我能够同步检查卡元素是否有错误,或者至少同步触发更改事件,但这似乎都不可能。

\n

Jus*_*ael 8

Stripe.js 根据元素的状态将多个类应用于每个 Stripe 元素的容器:

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

您可以在Stripe 的文档中阅读有关这些类的更多信息,包括如何自定义它们。

听起来检查类StripeElement--empty可能足以满足您的用例。你可以这样做:

const cardElementContainer = document.querySelector('#card-element');

let cardElementEmpty = cardElementContainer.classList.contains('StripeElement--empty');

// Do things based on cardElementEmpty being true or false
Run Code Online (Sandbox Code Playgroud)

  • 我相信对于“confirmCardPayment”,您需要提交有效的“PaymentIntent”,而我想首先在设置“PaymentIntent”之前验证该卡。 (4认同)