这是以前写的代码。当时是看着后台校验改编的,是可用的!
/**组织机构代码校验*/
-(BOOL)isValidEntpCode {
NSString *str = @"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
if (self.length==18) {
Byte ws[] = {1,3,9,27,19,26,16,17,20,29,25,13,8,24,10,30,28};
NSString *reg = @"^([0-9A-HJ-NPQRTUWXY]{2})([0-9]{6})([0-9A-HJ-NPQRTUWXY]{9})([0-9A-Z]{1})$";
NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", reg];
if (![regextestcm evaluateWithObject:self]) {
return NO;
}
NSArray *codes = [NSArray arrayWithObjects:[[self substringWithRange:NSMakeRange(0, self.length-1)] LY_defaultValue:@""],[[self substringWithRange:NSMakeRange(self.length-1, 1)] LY_defaultValue:@""], nil];
LYLog(@"%@",codes[0])
int sum = 0;
NSString *codeArr = codes[0];
for (int i = 0; i < 17; i++) {
NSString *strS = [codeArr substringWithRange:NSMakeRange(i, 1)];
NSRange range = [str rangeOfString:strS];
if (range.location!=NSNotFound) {
NSInteger strInt = range.location;
sum = sum + (int)strInt*ws[i];
} else {
return NO;
}
}
int c18 = 31 - (sum % 31);
NSRange rang = [str rangeOfString:codes[1]];
int c18t = (int)(rang.location);
if (c18==c18t) {
return YES;
} else {
return NO;
}
} else if (self.length==10) {
Byte ws[] = {3, 7, 9, 10, 5, 8, 4, 2 };
NSString *reg = @"^([0-9A-Z]){8}-[0-9|X]$";
NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", reg];
if (![regextestcm evaluateWithObject:self]) {
return NO;
}
int sum = 0;
for (int i = 0; i < 8; i++) {
NSString *strS = [self substringWithRange:NSMakeRange(i, 1)];
NSRange range = [str rangeOfString:strS];
if (range.location!=NSNotFound) {
NSInteger strInt = range.location;
sum = sum + (int)strInt*ws[i];
} else {
return NO;
}
}
int c9 = 11 - (sum % 11);
NSString *strT = [self substringWithRange:NSMakeRange(9, 1)];
NSRange rang = [str rangeOfString:strT];
int c9t = (int)(rang.location);
if (c9==c9t) {
return YES;
} else {
return NO;
}
}
return NO;
}
上面用到了LY_defaultValue,就是判断是否为空,下面是内部实现
- (id)LY_defaultValue:(id)defaultData {
if (![defaultData isKindOfClass:[self class]]) {
return defaultData;
}
if ([self LY_isEmptyObject]) {
return defaultData;
}
return self;
}
- (BOOL)LY_isEmptyObject {
if ([self isEqual:[NSNull null]]) {
return YES;
}
if ([self isKindOfClass:[NSString class]]) {
if ([(NSString *)self length] == 0) {
return YES;
}
}
if ([self isKindOfClass:[NSArray class]]) {
if ([(NSArray *)self count] == 0) {
return YES;
}
}
if ([self isKindOfClass:[NSDictionary class]]) {
if ([(NSDictionary *)self count] == 0) {
return YES;
}
}
return NO;
}