Reputation: 460
I have a payment flow using the following react stripe elements.
I'm using the onChange prop to display real-time errors as the user types. I also want these errors to show when the user hits the submit button. For example, if they don't fill any of the fields out and they click submit the following errors would show. However, the only way I have found to do this is by calling stripe.createPaymentMethod() which takes a couple of seconds to return a response and feels sluggish. What exactly does the onChange prop use under the hood to validate the input field and how can I use it instead of createPaymentMethod()?
Upvotes: 2
Views: 6755
Reputation: 55
An easier solution I found was to use Stripe's useElements
to create an elements object:
const elements = useElements();
Subsequently, you can use this to grab the element you are interested in and check it's _invalid
and _empty
properties.
const cardNumber = elements.getElement('cardNumber');
const isInvalid = cardNumber._invalid;
const isEmpty = cardNumber._empty;
const isValid = !isEmpty && !isInvalid;
Note: The input is NOT considered invalid when it is empty.
Not sure why there isn't an easier method, but hey.
Upvotes: 3
Reputation: 6460
You can listen to the change
event on Stripe Elements and look for event.error
on the event
passed to your event handler to handle input validation.
When a Stripe Element loses focus and the value it contains does not appear to be valid event.error
will be populated and contain a code
, message
, and type
which you can use to update the Element's appearance and display the message
to the user.
For example, when you provide a partial card number and switch focus to another field event.error
will contain the following:
"error": {
"code": "incomplete_number",
"type": "validation_error",
"message": "Your card number is incomplete."
},
Upvotes: 3