最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
js怎么判断用户输入的银行卡号是否正确 判断方法
时间:2022-06-29 00:41:53 编辑:袖梨 来源:一聚教程网
开发中,有时候,为了打造更好的用户体验,同时减轻服务器端的压力,需要对于一些如,手机号码,银行卡号,身份证号码进行格式校验
下面是判断银行卡号输入是否正确的代码(基于Luhn算法的格式校验):
iOS代码:
* 银行卡格式校验
* @param cardNo 银行卡号
*
* @return
*/
+ (BOOL) checkCardNo:(NSString*) cardNo{
int oddsum = 0; //奇数求和
int evensum = 0; //偶数求和
int allsum = 0;
int cardNoLength = (int)[cardNo length];
int lastNum = [[cardNo substringFromIndex:cardNoLength-1] intValue];
cardNo = [cardNo substringToIndex:cardNoLength - 1];
for (int i = cardNoLength -1 ; i>=1;i--) {
NSString *tmpString = [cardNo substringWithRange:NSMakeRange(i-1, 1)];
int tmpVal = [tmpString intValue];
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 YES;
else
return NO;
}
Androd代码:
/**
* 匹配Luhn算法:可用于检测银行卡卡号
* @param cardNo
* @return
*/
publicstaticbooleanmatchLuhn(String cardNo) {
int[] cardNoArr =newint[cardNo.length()];
for(inti=0; i cardNoArr[i] = Integer.valueOf(String.valueOf(cardNo.charAt(i))); } for(inti=cardNoArr.length-2;i>=0;i-=2) { cardNoArr[i] <<=1; cardNoArr[i] = cardNoArr[i]/10+ cardNoArr[i]%10; } intsum =0; for(inti=0;i sum += cardNoArr[i]; } returnsum %10==0; } 附(银行卡号格式化): 在输入银行卡号过程中,通常,我们会每隔4位插入一个"-",类似"1332-2131-2313-1231-212"这种的格式 设置textField的代理 - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { NSString *text = [textField text]; NSCharacterSet *characterSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789b"]; string = [string stringByReplacingOccurrencesOfString:@"-" withString:@""]; if ([string rangeOfCharacterFromSet:[characterSet invertedSet]].location != NSNotFound) { return NO; } text = [text stringByReplacingCharactersInRange:range withString:string]; text = [text stringByReplacingOccurrencesOfString:@"-" withString:@""]; NSString *newString = @""; while (text.length > 0) { NSString *subString = [text substringToIndex:MIN(text.length, 4)]; newString = [newString stringByAppendingString:subString]; if (subString.length == 4) { newString = [newString stringByAppendingString:@"-"]; } text = [text substringFromIndex:MIN(text.length, 4)]; } newString = [newString stringByTrimmingCharactersInSet:[characterSet invertedSet]]; if (newString.length >= 24) { return NO; } [textField setText:newString]; return NO; } 最后,怎么获得不包含符号"-"的银行卡号呢? [self.textField.text stringByReplacingOccurrencesOfString:@"-" withString:@""] 以上这篇判断用户输入的银行卡号是否正确的方法(基于Luhn算法的格式校验)就是小编分享给大家的全部内容了,希望能给大家一个参考,对大家有所帮助。
可以通过以下方法实现:相关文章