输入银行卡号要自限制?我有好方法!
校验银行卡号?我有好方法!
构建思路
- 选择合适的键盘
- 输入时进行调整
- 结束编辑再次调整
核心规避风险
贴代码演示
class:superclass<UIUITextFieldDelegate>
self.CardNoField.text = [[UITextField alloc]init];
self.CardNoField.delegate = self;
- 键盘设置建议使用的键盘
UIKeyboardTypeNumberPad
self.CardNoField.keyboardType = UIKeyboardTypeNumberPad;
代理中应做的:
- 编辑时
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
NSLog(@"%@",string);
if ([string isEqualToString:@" "]) {
return NO;
}
if(self.CardNoField == textField){
if ([string isEqualToString:@"."]&&newLength == 18) {
textField.text = [NSString stringWithFormat:@"%@X",textField.text];
return NO;
}if ([string isEqualToString:@"."]) {
return NO;
}
NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789"] invertedSet];
NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
return [string isEqualToString:filtered]&&newLength <= 19? YES :NO ;
}
return newLength <= 16;
}
- 结束编辑再次调整
- (void)textFieldDidEndEditing:(UITextField *)textField;{
if (self.CardNoField== textField) {
NSCharacterSet *setToRemove = [[ NSCharacterSet characterSetWithCharactersInString:@"0123456789"]
invertedSet ];
textField.text = [[textField.text componentsSeparatedByCharactersInSet:setToRemove] componentsJoinedByString:@""];
}
}
- 校验是否正确
+ (BOOL) checkCardNo:(NSString*) cardNo{
if (cardNo.length<15) {
return NO;
}
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;
}
网友评论