Validating custom Stripe form
← Examples
Stripe is a popular payment platform. It's quite easy for developers to use and integrate its helpful APIs in a payment, checkout form.
This example covers steps to help you create a payment form with Bootstrap framework, validate it with FormValidation. The credit card data is then processed by Stripe API.
Step 1: Creating a payment form
It's easy to use your favorite framework to create a standard payment form as following:
As you see, all fields for filling the credit card information don't have the name
attribute. Instead, they use the data-stripe
attribute which are defined by Stripe. The Stripe API then will collects the credit card data from fields using this attribute.
The form also includes a hidden field named token
. Instead of storing the credit card data which are very sensitive, the form stores an equivalent token that is determined and returned by Stripe API.
Step 2: Adding validation rules
All credit card fields are nameless elements. How we can apply the validation rules for them?
Fortunately, FormValidation provides the selector option to support indicating fields via a CSS selector.
We can use the built in validators for the credit card fields via their data-stripe
attribute as following:
The table below list validators used for validating credit card data:
Validator | Purpose |
---|---|
creditCard | Validate a credit card number |
cvv | Validate a CVV number |
callback | Validate expiration month and year. For more details, see the Validating credit card expiration date example. |
Step 3: Using Stripe API to collect credit card data
When the form passes our validation rules, it's time to send credit card data to Stripe and get back the token. It can be done by triggering the success.form.fv event:
Inside the handler of Stripe.card.createToken
, we use bootboxjs to show the error message from Stripe if there's something wrong with credit card data. Otherwise, we set the token value returned by Stripe API. This token then can be used to charge the customer.
Optionally, you can use the resetForm() method to reset entire form in case you use Ajax to send the form data to server.
You can see how all the steps are implemented in the working example below. We also provide some fake credit card numbers for testing:
Card type | Example |
---|---|
American Express | 340653705597107 |
Diners Club | 30130708434187 |
Diners Club (US) | 5517479515603901 |
Discover | 6011734674929094 |
JCB | 3566002020360505 |
Maestro | 6762835098779303 |
Mastercard | 5303765013600904 |
Visa | 4929248980295542 |