Stripe 建议使用 change
card
的客户端验证事件元素:
cardElement.on('change', function(event) {
if (event.complete) {
// enable payment button
} else if (event.error) {
// show validation to customer
}
});
但是,如果用户从不编辑/更改卡片元素,则这种方法无法确定卡片元素无效。我总是可以尝试使用 confirmCardPayment
提交付款但这是低效的——这种验证应该可以在客户端进行。我可以通过将付款表单默认为错误状态来解决此问题,然后在用户第一次更改卡时解决(或不解决)。但是,这并不方便,因为它需要我将应用程序代码中的“您的卡号不完整”错误消息国际化,而不是依赖 Stripe。
理想情况下,我将能够同步检查卡元素是否有错误,或者至少同步触发更改事件,但这些似乎都不可能。
最佳答案
Stripe.js 根据元素的状态将几个类应用于每个 Stripe 元素的容器:
StripeElement--complete
StripeElement--empty
StripeElement--focus
StripeElement--invalid
StripeElement--webkit-autofill
(仅限 Chrome 和 Safari)您可以在 Stripe's documentation 中阅读有关这些类的更多信息,包括如何自定义它们。 .
听起来像是在检查
StripeElement--empty
类可能足以满足您的用例。你可以这样做:const cardElementContainer = document.querySelector('#card-element');
let cardElementEmpty = cardElementContainer.classList.contains('StripeElement--empty');
// Do things based on cardElementEmpty being true or false
关于javascript - Stripe 元素 : how can I validate a card element is not blank client-side?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65862556/