Method package for verifying bank card number

Premise: Since general regular expressions cannot meet the needs, I wrote a method for bank card numbers to verify the value of the input card number and return true or false. After testing, the accuracy rate is still very high. If you need it, you can try it. Give it a try.

Method encapsulation:

// 卡号校验方法封装
isBankAccount(str) {
    
    
	if (str.length == 0) {
    
    
		return false;
	}
	var oddsum = 0; //奇数求和
	var evensum = 0; //偶数求和
	var allsum = 0;
	var cardNoLength = str.length;
	var lastNum = parseInt(str.charAt(cardNoLength - 1));

	var cardNo = str.substring(0, cardNoLength - 1);
	for (var i = cardNoLength - 1; i >= 1; i--) {
    
    
		var tmpString = cardNo.substring(i - 1, i);
		var tmpVal = parseInt(tmpString);
		if (cardNoLength % 2 == 1) {
    
    
			if (i % 2 == 0) {
    
    
				tmpVal *= 2;
				if (tmpVal >= 10) {
    
    
					tmpVal -= 9;
				}
				evensum += tmpVal;
			} else {
    
    
				oddsum += tmpVal;
			}
		} else {
    
    
			if (i % 2 == 1) {
    
    
				tmpVal *= 2;
				if (tmpVal >= 10) {
    
    
					tmpVal -= 9;
				}
				evensum += tmpVal;
			} else {
    
    
				oddsum += tmpVal;
			}
		}
	}
	allsum = oddsum + evensum;
	allsum += lastNum;
	if (allsum % 10 == 0) {
    
    
		return true;
	} else {
    
    
		return false;
	}
},

Usage example:

<uni-easyinput type="number" trim="all" :value="settleCardValue" placeholder="请输入卡号" :inputBorder="false" @input="settleCardChange"/>
settleCardChange(value) {
    
    
	let res = this.isBankAccount(value)
	// 输入卡号的值 >11位时,再校验该方法,更准确
	if (value.length > 11) {
    
    
		console.log(res);  // true/false
		// 判断卡号是否正确,true则正确,false则输入错误
		// 可通过 true / false 做出一些处理...
		if(res == true){
    
    
			// TODO: 卡号输入正确,可调接口等操作...
			
		}
	}
}

Ending: Here I need to identify the card number, and then adjust the interface to echo the bank name; so when the card number is entered correctly, call the interface again. This can avoid calling the interface multiple times and reduce performance problems.

Rest time~
Insert image description here

Guess you like

Origin blog.csdn.net/m0_58953167/article/details/132854676