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.
By not using the name attribute for sensitive fields, we can prevent them from sending to the server when the form is submitted.
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 expiration month (expMonth) and year (expYear) fields use the row option to indicate that they're placed inside a custom container instead of a default Bootstrap .form-group one
The table below list validators used for validating credit card data:
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: