Skip to content

Issue #2790551 by steveoliver, bojanz, borisson_: Implement a JS libr… #663

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: 8.x-2.x
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions modules/payment/commerce_payment.libraries.yml
Original file line number Diff line number Diff line change
@@ -1,3 +1,10 @@
credit_card_validation:
version: VERSION
js:
js/credit-card-validation.js: {}
dependencies:
- core/jquery

payment_method_form:
version: VERSION
css:
Expand Down
258 changes: 258 additions & 0 deletions modules/payment/js/credit-card-validation.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,258 @@
/**
* @file
* Attaches credit card validation logic.
*/

(function ($) {

'use strict';

var types = {};
var VISA = 'visa';
var MASTERCARD = 'master-card';
var AMEX = 'amex';
var DINERSCLUB = 'dinersclub';
var DISCOVER = 'discover';
var MAESTRO = 'maestro';
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We're missing JCB and UnionPay.


types[VISA] = {
niceType: 'Visa',
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why niceType and not label?
And why aren't the labels passed through Drupal.t()?

type: VISA,
pattern: ['4'],
gaps: [4, 8, 12],
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Gaps are not used anywhere, and don't exist on the PHP side, let's remove them.

lengths: [16]
};

types[MASTERCARD] = {
niceType: 'MasterCard',
type: MASTERCARD,
pattern: ['51-55', '222100-272099'],
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"pattern" should be "prefixes" to match the PHP code.

gaps: [4, 8, 12],
lengths: [16]
};

types[AMEX] = {
niceType: 'American Express',
type: AMEX,
pattern: ['34', '37'],
lengths: [15]
};

types[DINERSCLUB] = {
niceType: 'Diners Club',
type: DINERSCLUB,
pattern: ['300-305', '309', '36', '38', '39'],
lengths: [14]
};

types[DISCOVER] = {
niceType: 'Discover Card',
type: DISCOVER,
pattern: ['6011', '622126-622925', '644-649', '65'],
lengths: [16, 19]
};

types[MAESTRO] = {
niceType: 'Maestro',
type: MAESTRO,
pattern: [
'5018',
'5020',
'5038',
'5612',
'5893',
'6304',
'6759',
'6761',
'6762',
'6763',
'0604',
'6390'
],
lenghts: [12, 13, 14, 15, 16, 17, 18, 19]

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should be lengths

};


/**
* Detect the type of credit card.
*
* @param {string} number
*
* @return {object|boolean}
*/
var detectType = function (number) {
// Loop over all available types.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Comments that retell what the code is doing ("Loop over all the available types") aren't useful, let's remove them.

for (var x in types) {
var type = types[x];

// Loop over all patterns in the type.
for (var i in type.pattern) {
var pattern = type.pattern[i];
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why don't we introduce a matchPrefix() helper like we did in PHP?
On the other hand, validatePrefix() could probably be inlined.


// If the pattern has a dash, we should create a range of patterns.
if (pattern.indexOf('-') >= 0) {
var exploded_pattern;
var ranges = [];
var range;
exploded_pattern = pattern.split('-');

while (exploded_pattern[0] <= exploded_pattern[1]) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This feels overly complex.
We reimplementing the following code:

      list($start, $end) = explode('-', $prefix);
      $number = substr($number, 0, strlen($start));
      return $number >= $start && $number <= $end;

ranges.push(exploded_pattern[0]);
exploded_pattern[0]++;
}

for (range in ranges) {
if (validatePrefix(number, range)) {
return type;
}
}
}
// No dashes, so just validate this pattern.
else if (validatePrefix(number, pattern)) {
return type;
}
}
}

return false;
};

/**
* Validate the prefix is according to the expected prefix.
*
* @param {string} number
* @param {string} prefix
*
* @return {boolean}
*/
var validatePrefix = function (number, prefix) {
return number.substring(0, prefix.length) == prefix + '';
};

/**
* Validate credit card.
*
* @param {string} number
* @param {object} type
*
* @return {boolean}
*/
var validateCreditCard = function (number, type) {
// Make sure that the type is really the expected type.
if (detectType(number) != type) {
return false;
}

// Test that the length of the card is actually one of the expected lengths
// defined in the type.
for (var x in type.lengths) {
var expected_lenght = type.lengths[x];
if (number.length === expected_lenght) {
return true;
}
}

return false;
};

/**
* Trigger all other validations.
*
* @param {object} element
*/
var cardInputBlur = function (element) {
var value = element.val();
// Strip spaces from the value for all validations.
value = value.replace(/ /gi, '');

// If the value is not filled in, don't do any validation.
var empty_value = value.length === 0;
if (empty_value) {
element.addClass('invalid-cc');
return;
}

// Get the type of the card.
var type = detectType(value);

// If no type is found, don't bother doing anything else.
if (!type) {
element.addClass('invalid-cc');
return;
}
element.addClass('credit_card');
element.addClass('credit_card--' + type.type);

var ValidationDiv = element.parent().parent().find('#cc-validation');
ValidationDiv.html('');

var ccv_field = $("input[name='payment_information[add][payment_details][security_code]']");
if (ccv_field.size() > 0) {
var ccv_value = ccv_field.val();
if (ccv_value.length == 0) {
ValidationDiv.append('CCV is not filled in');
return;
}
}

ValidationDiv.append('CC is of type: ' + type.niceType);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This looks like debug code?


// Check if the card is actually valid as well.
var is_valid = validateCreditCard(value, type);
if (is_valid) {
ValidationDiv.append(' CC is valid');
element.removeClass('invalid-cc');
element.addClass('valid-cc');
}
else {
ValidationDiv.append(' CC is not valid');
element.removeClass('valid-cc');
element.addClass('invalid-cc');
}
};

/**
* Element onkey upvalidation.
*
* @param {object} element
*/
var cardInputKeyup = function (element) {
var value = element.val();
// Strip spaces from the value for all validations.
value = value.replace(/ /gi, '');

// If the value is not filled in, don't do any validation.
var empty_value = value.length === 0;
if (empty_value) {
element.addClass('invalid-cc');
return;
}

// Get the type of the card.
var type = detectType(value);

// If no type is found, don't bother doing anything else.
if (!type) {
element.addClass('invalid-cc');
return;
}
element.removeClass('invalid-cc');
element.addClass('credit_card');
element.addClass('credit_card--' + type.type);
};

Drupal.behaviors.creditCardValidation = {
attach: function (context, settings) {
$('#edit-payment-information-add-payment-details-number', context).each(function () {
var element = $(this);
$(element).on('blur', function () {
cardInputBlur(element);
});
$(element).on('keyup', function() {
cardInputKeyup(element);
});
});
}
};

})(jQuery);
2 changes: 2 additions & 0 deletions modules/payment/src/PluginForm/PaymentMethodAddForm.php
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ public function buildConfigurationForm(array $form, FormStateInterface $form_sta
];
if ($payment_method->bundle() == 'credit_card') {
$form['payment_details'] = $this->buildCreditCardForm($form['payment_details'], $form_state);
$form['#attached']['library'][] = 'commerce_payment/credit_card_validation';
}
elseif ($payment_method->bundle() == 'paypal') {
$form['payment_details'] = $this->buildPayPalForm($form['payment_details'], $form_state);
Expand Down Expand Up @@ -173,6 +174,7 @@ protected function buildCreditCardForm(array $element, FormStateInterface $form_
'#required' => TRUE,
'#maxlength' => 19,
'#size' => 20,
'#suffix' => '<div id="cc-validation"></div>',
];
$element['expiration'] = [
'#type' => 'container',
Expand Down