bob*_*obb 5 javascript jquery credit-card
我正在编写一个工具,onkeydown将运行输入框中输入的当前值,以检查它是否与4种主要类型的信用卡之一的正则表达式匹配.
我觉得它有点工作,但它是片状的,所以我想弄清楚是什么导致它给出错误的响应(例如,有时它会输出2个值而不是1个).是因为我需要在循环之前设置一个标志变量吗?在匹配正确的卡片后,我只是从环路中穿过物体返回,所以我认为这足够了......
正则表达式的标准来自此站点:
签证:^4[0-9]{12}(?:[0-9]{3})?$所有Visa卡号码均以4开头.新卡有16位数字.旧卡有13个.
万事达卡:^5[1-5][0-9]{14}$所有万事达卡号码都以数字51到55开头.全部有16位数字.
美国运通:^3[47][0-9]{13}$美国运通卡号码开始与34或37,并有15位数字.
发现:^6(?:011|5[0-9]{2})[0-9]{12}$发现卡号以6011或65开头.全部有16位数字.
$(function() {
var $cardNumber = $('#js-cardnumber');
var ccMap = {};
ccMap.cards = {
'amex': '^3[47][0-9]{13}$',
'discover': '^6(?:011|5[0-9]{2})[0-9]{12}$',
'mastercard': '^5[1-5][0-9]{14}$',
'visa': '^4[0-9]{12}(?:[0-9]{3})?$'
};
$cardNumber.keydown(function() {
for (var cardType in ccMap.cards) {
if (ccMap.cards.hasOwnProperty(cardType)) {
var regex = ccMap.cards[cardType];
if (regex.match($(this).val())) {
console.log(cardType);
return;
}
}
}
});
});?
Run Code Online (Sandbox Code Playgroud)您似乎以错误的方式使用正则表达式。
如果要根据正则表达式检查字符串,可以使用match()字符串的方法:
string.match(regexp) // returns boolean
Run Code Online (Sandbox Code Playgroud)
你这样做的方式是错误的:
if ( regex.match($(this).val()) ) {
Run Code Online (Sandbox Code Playgroud)
尝试将当前值解释为正则表达式。一定是这样的:
if ( $(this).val().match(regex) ) {
Run Code Online (Sandbox Code Playgroud)
您还可以缓存正则表达式以使脚本更加高效:
ccMap.cards = {
'amex': /^3[47][0-9]{13}$/, // store an actual regexp object, not a string
// ...
// The way you test changes, now you're able to use the "test"
// method of the regexp object:
if ( regex.test($(this).val()) ) {
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1928 次 |
| 最近记录: |