Skip to content

Instantly share code, notes, and snippets.

@coop
Last active December 27, 2015 03:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save coop/7262638 to your computer and use it in GitHub Desktop.
Save coop/7262638 to your computer and use it in GitHub Desktop.
//= require jquery.payment
jQuery(function($) {
var $form = $('form#donation-form'),
$submit = $('input[type=submit]', $form);
// Fields can be invalid in two ways:
//
// * do not contain a value
// * fail $.payment checks
//
// The first condition is caught by the second but only after the field has
// had focus. A good example of this is on page load, the form is
// considered invalid but we don't want to show that to the user until they
// interact with the field.
var validationCheck = function(field, validity, callback) {
$(field).toggleClass('invalid', !validity);
var anyEmptyCreditCardFields = $('.cc', $form).filter(function() {
return this.value == '';
}).length > 0,
anyInvalidCreditCardFields = $('input.invalid', $form).length > 0,
isFormValid = !(anyEmptyCreditCardFields || anyInvalidCreditCardFields);
if (typeof callback == 'function') callback(validity);
toggleSubmitButton(isFormValid);
};
var toggleSubmitButton = function(value) {
var disabledClass = 'donate--disabled',
enabledClass = 'donate';
if(value) {
$submit
.removeClass(disabledClass)
.addClass(enabledClass);
} else {
$submit
.removeClass(enabledClass)
.addClass(disabledClass);
}
$submit.prop('disabled', !value);
};
$('.cc-number', $form)
.payment('formatCardNumber')
.on('blur', function() {
validationCheck(this, $.payment.validateCardNumber(this.value));
});
$('.cc-exp', $form)
.payment('formatCardExpiry')
.on('blur', function() {
var expiry = $(this).payment('cardExpiryVal'),
callback = function(validity) {
if(validity) {
$('.cc-exp-month').val(expiry.month);
$('.cc-exp-year').val(expiry.year);
}
};
validationCheck(this, $.payment.validateCardExpiry(expiry), callback);
});
$('.cc-cvv', $form)
.payment('formatCardCVC')
.on('blur', function() {
var cardType = $.payment.cardType($('.cc-number', $form).val());
validationCheck(this, $.payment.validateCardCVC(this.value, cardType));
});
$form.submit(function(event) {
event.preventDefault();
toggleSubmitButton(true);
$form.get(0).submit();
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment