@@ -13,24 +13,60 @@ $(document).on('turbolinks:load', function(){
13
13
submitBtn . click ( function ( event ) {
14
14
// prevent default submission behavior.
15
15
event . preventDefault ( ) ;
16
+ submitBtn . val ( "Processing" ) . prop ( 'disabled' , true ) ;
16
17
17
18
// Collect the credit card fields.
18
19
var ccNum = $ ( '#card_number' ) . val ( ) ,
19
20
cvcNum = $ ( '#card_code' ) . val ( ) ,
20
21
expMonth = $ ( '#card_month' ) . val ( ) ,
21
22
expYear = $ ( '#card_year' ) . val ( ) ;
22
23
23
- // Send the card info to Stripe.
24
- Stripe . createToken ( {
25
- number : ccNum ,
26
- cvc : cvcNum ,
27
- exp_month : expMonth ,
28
- exp_year : expYear
29
- } , stripeResponseHandler ) ;
24
+ // Use Stripe JS library to check for card errors.
25
+ var error = false ;
26
+
27
+ // Validate card number.
28
+ if ( ! Stripe . card . validateCardNumber ( ccNum ) ) {
29
+ error = true ;
30
+ alert ( 'The credit card number appears to be invalid.' ) ;
31
+ }
32
+
33
+ // Validate CVC number.
34
+ if ( ! Stripe . card . validateCVC ( cvcNum ) ) {
35
+ error = true ;
36
+ alert ( 'The CVC number appears to be invalid.' ) ;
37
+ }
38
+
39
+ // Validate expiration date.
40
+ if ( ! Stripe . card . validateExpiry ( expMonth , expYear ) ) {
41
+ error = true ;
42
+ alert ( 'The expiration date appears to be invalid.' ) ;
43
+ }
44
+
45
+ if ( error ) {
46
+ // If there are card errors, don't send to Stripe.
47
+ submitBtn . prop ( 'disabled' , false ) . val ( "Sign Up" ) ;
48
+ } else {
49
+ // Send the card info to Stripe.
50
+ Stripe . createToken ( {
51
+ number : ccNum ,
52
+ cvc : cvcNum ,
53
+ exp_month : expMonth ,
54
+ exp_year : expYear
55
+ } , stripeResponseHandler ) ;
56
+ }
57
+
58
+ return false ;
30
59
} ) ;
31
-
32
60
33
61
// Stripe will return a card token.
34
- // Inject card token as hidden field into form.
35
- // Submit form to our Rails app.
62
+ function stripeResponseHandler ( status , response ) {
63
+ // Get the token from the response.
64
+ var token = response . id ;
65
+
66
+ // Inject card token as hidden field into form.
67
+ theForm . append ( $ ( '<input type="hidden" name="user[stripe_card_token]">' ) . val ( token ) ) ;
68
+
69
+ // Submit form to our Rails app.
70
+ theForm . get ( 0 ) . submit ( ) ;
71
+ }
36
72
} ) ;
0 commit comments