patternjavascriptMinor
Calling a Luhn check function when a credit card field changes
Viewed 0 times
fieldcheckcreditfunctioncardchangeswhencallingluhn
Problem
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.');
}
});Solution
$(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.');
}));
});Code Snippets
$(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.');
}
});
});$(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.');
}));
});Context
StackExchange Code Review Q#12538, answer score: 2
Revisions (0)
No revisions yet.