Is there a better way to do a Luhn check?

I feel like I should not be duplicating the code to gather the credit card number, but I am not sure how best to do it. Any suggestions?

$('input[name="payment\[cc_number\]"]').keyup(function() {
    var ccNum = $(this).val();
    ccNum = ccNum.replace(/[^\d]/g, '');
    setSelectValue(ccNum);
});

$('input[name="payment\[cc_number\]"]').blur(function(ccNum) {
    var ccNum = $(this).val();
    ccNum = ccNum.replace(/[^\d]/g, '');
    if (!luhnCheck(ccNum)) {
        alert('Please enter a valid credit card number.');
    }
});

Answers


$(function() {
  // Always select a context and use it as the second parameter 
  // it will make everything far faster and less prone to errors
  var form = $('form'); 
  var stripCcNum = function(el) {
      return $(this).val().replace(/[^\d]/g, '');
  }

  $('input[name="payment\[cc_number\]"]', form).keyup(function() {

    setSelectValue(stripCcNum(this));

  }).blur(function(ccNum) {

    if (!luhnCheck( stripCcNum(this) )) {
        alert('Please enter a valid credit card number.');
    }

  });

});

Or for the totally and absolute 1337 (meaning you shouldn't do it for something this simple but it demonstrates some useful techniques)

$(function() {
  var form = $('form'),
    handleCcNum = function(doThis) {
      return function() { 
        doThis.call(this, $(this).val().replace(/[^\d]/g, ''));
      }
    }

  $('input[name="payment\[cc_number\]"]', form)
    .keyup( handleCcNum(function(num) { setSelectValue(num); } )
    .blur( handleCcNum(function(num) { 
       !luhnCheck(num) && alert('Please enter a valid credit card number.');
    }));
});

Need Your Help

What is the advantage of Gmail's client side web architecture?

javascript gmail

I was just wondering what is the advantage of client side architecture GMail is following.

Using PKCS 7 Cryptography

java cryptography openssl keytool pkcs#7

I need to encrypt and sign data using PKCS7(CMS).