IOS校验验证手机号,信用卡号,电话号码,邮编,Email等

下面是编程之家 jb51.cc 通过网络收集整理的代码片段。

编程之家小编现在分享给大家,也给大家做个参考。

#import <Foundation/Foundation.h>

typedef enum 
{
    IdentifierTypeKNown = 0,IdentifierTypeZipCode,//1
    IdentifierTypeEmail,//2
    IdentifierTypePhone,//3
    IdentifierTypeUnicomPhone,//4    
    IdentifierTypeQQ,//5
    IdentifierTypeNumber,//6
    IdentifierTypestring,//7
    IdentifierTypeIdentifier,//8
    IdentifierTypePassort,//9
    IdentifierTypeCreditNumber,//10
    IdentifierTypeBirthday,//11 
}IdentifierType;

@interface IdentifierValidator : NSObject
{
}

+ (BOOL) isValid:(IdentifierType) type value:(Nsstring*) value;

@end

#import "IdentifierValidator.h"
#import "Nsstring+ITTAdditions.h"

int getIndex (char ch);
BOOL isNumber (char ch);

int getIndex (char ch) {
    if ((ch >= '0'&& ch <= '9')||(ch >= 'a'&& ch <= 'z')||
        (ch >= 'A' && ch <= 'Z')|| ch == '_') {
        return 0;
    }
    if (ch == '@') {
        return 1;
    }
    if (ch == '.') {
        return 2;
    }
    return -1;
}

BOOL isNumber (char ch)
{
    if (!(ch >= '0' && ch <= '9')) {
        return FALSE;
    }
    return TRUE;
}
@implementation IdentifierValidator

+ (BOOL) isValidZipcode:(Nsstring*)value 
{
    const char *cvalue = [value UTF8String];
    int len = strlen(cvalue);
    if (len != 6) {
        return FALSE;
    }
    for (int i = 0; i < len; i++) 
    {
        if (!(cvalue[i] >= '0' && cvalue[i] <= '9')) 
        {
            return FALSE;
        }
    }
    return TRUE;
}

+ (BOOL) validateEmail:(Nsstring *)candidate
{
    NSArray *array = [candidate componentsSeparatedByString:@"."];
    if ([array count] >= 4) {
        return FALSE;
    }
    Nsstring *emailRegex = @"[A-Z0-9a-z._%+-][email protected][A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"; 
    nspredicate *emailTest = [nspredicate predicateWithFormat:@"SELF MATCHES %@",emailRegex]; 
    return [emailTest evaluateWithObject:candidate];
}

+ (BOOL) isValidEmail:(Nsstring*)value {
    static int state[5][3] = {
        {1,-1,-1},{1,2,{3,4},{4,-1}
    };
    BOOL valid = TRUE;
    const char *cvalue = [value UTF8String];
    int currentState = 0;
    int len = strlen(cvalue);
    int index;
    for (int i = 0; i < len && valid; i++) {
        index = getIndex(cvalue[i]);
        if (index < 0) {
            valid = FALSE;
        }
        else {
            currentState = state[currentState][index];
            if (currentState < 0) {
                valid = FALSE;
            }
        }
    }
    //end state is invalid
    if (currentState != 4) {
        valid = FALSE;
    }
    return valid;
}

+ (BOOL) isValidNumber:(Nsstring*)value{
    const char *cvalue = [value UTF8String];
    int len = strlen(cvalue);
    for (int i = 0; i < len; i++) {
        if(!isNumber(cvalue[i])){
            return FALSE;
        }
    }
    return TRUE;
}

+ (BOOL) isValidPhone:(Nsstring*)value {
    const char *cvalue = [value UTF8String];
    int len = strlen(cvalue);
    if (len != 11) {
        return FALSE;
    }
    if (![IdentifierValidator isValidNumber:value]) 
    {
        return FALSE;
    }
    Nsstring *preString = [[Nsstring stringWithFormat:@"%@",value] substringToIndex:2];    
    if ([preString isEqualToString:@"13"] ||
        [preString isEqualToString: @"15"] || 
        [preString isEqualToString: @"18"]) 
    {
        return TRUE;
    }
    else
    {
        return FALSE;
    }
    return TRUE;
}
+ (BOOL) isValidString:(Nsstring*)value 
{
    return value && [value length];
}
const int factor[] = { 7,9,10,5,8,4,1,6,3,7,2 };//加权因子 
const int checktable[] = { 1,2 };//校验值对应表
+ (BOOL) isValidIdentifier:(Nsstring*)value 
{
    const int LENGTH = 18;    
    const char *str = [[value lowercaseString] UTF8String];
    NSInteger i;    
    NSInteger length = strlen(str);
    BOOL result = TRUE;    
    /*
     * identifier length is invalid
     */
    if (15 != length && LENGTH != length)
    {
        result = FALSE;
    }
    else
    {
        for (i = 1; i < length - 1; i++)
        {
            if(!(str[i] >= '0' && str[i] <= '9')) 
            {
                result = FALSE;
                break;
            }
        }
        if (result) 
        {
            if(LENGTH == length)
            {
                if (!((str[i] >= '0' && str[i] <= '9')||str[i] == 'X'||str[i] == 'x'))
                {
                    result = FALSE;
                }
            }
        }
        /*
         * check sum for second generation identifier
         */
        if (result && length == LENGTH) 
        {
            int i;
            int *ids = malloc(sizeof(int)*LENGTH);
            for (i = 0; i < LENGTH; i++) 
            {
                ids[i] = str[i] - 48;             
            }
            int checksum = 0; 
            for (i = 0; i < LENGTH - 1; i ++ )
            {
                checksum += ids[i] * factor[i];
            }
            if (ids[17] == checktable[checksum%11]|| 
                (str[17] == 'x' && checktable[checksum % 11] == 10))  
            {
                result  = TRUE;
            }
            else 
            {
                result  = FALSE;            
            }
            free(ids);
            ids = NULL;
        }        
    }
    return result;
}
+ (BOOL) isValidPassport:(Nsstring*)value 
{
    const char *str = [value UTF8String];
    char first = str[0];
    NSInteger length = strlen(str);
    if (!(first == 'P' || first == 'G')) 
    {
        return FALSE;
    }
    if (first == 'P')
    {
        if (length != 8) 
        {
            return FALSE;
        }
    }
    if (first == 'G') 
    {
        if (length != 9) 
        {
            return FALSE;
        }
    }
    BOOL result = TRUE;
    for (NSInteger i = 1; i < length; i++) 
    {
        if (!(str[i] >= '0' && str[i] <= '9')) 
        {
            result = FALSE;
            break;
        }
    }        
    return result;
}
/*
 * 常用信用卡卡号规则
 * Issuer Identifier  Card Number                            Length
 * Diner's Club       300xxx-305xxx,3095xx,36xxxx,38xxxx  14
 * American Express   34xxxx,37xxxx                         15
 * VISA               4xxxxx                                 13,16
 * MasterCard         51xxxx-55xxxx                          16
 * JCB                3528xx-358xxx                          16
 * discover           6011xx                                 16
 * 银联                622126-622925                          16 
 *
 * 信用卡号验证基本算法: 
 * 偶数位卡号奇数位上数字*2,奇数位卡号偶数位上数字*2。
 * 大于10的位数减9。
 * 全部数字加起来。
 * 结果不是10的倍数的卡号非法。
 * prefrences link:http://www.truevue.org/licai/credit-card-no
 *
 */
+ (BOOL) isValidCreditNumber:(Nsstring*)value
{
    BOOL result = TRUE;
    NSInteger length = [value length];    
    if (length >= 13) 
    {
        result = [IdentifierValidator isValidNumber:value];    
        if (result) 
        {
            NSInteger twoDigitBeginValue = [[value substringWithRange:NSMakeRange(0,2)] integerValue];
            NSInteger threeDigitBeginValue = [[value substringWithRange:NSMakeRange(0,3)] integerValue];        
            NSInteger fourDigitBeginValue = [[value substringWithRange:NSMakeRange(0,4)] integerValue];        
            //Diner's Club
            if (((threeDigitBeginValue >= 300 && threeDigitBeginValue <= 305)||
                 fourDigitBeginValue == 3095||twoDigitBeginValue==36||twoDigitBeginValue==38) && (14 != length)) 
            {
                result = FALSE;
            }
            //VISA
            else if([value isstartWithString:@"4"] && !(13 == length||16 == length))
            {
                result = FALSE;
            }
            //MasterCard
            else if((twoDigitBeginValue >= 51||twoDigitBeginValue <= 55) && (16 != length))
            {
                result = FALSE;
            }        
            //American Express
            else if(([value isstartWithString:@"34"]||[value isstartWithString:@"37"]) && (15 != length))
            {
                result = FALSE;
            }  
            //discover
            else if([value isstartWithString:@"6011"] && (16 != length))
            {
                result = FALSE;
            }          
            else 
            {
                NSInteger begin = [[value substringWithRange:NSMakeRange(0,6)] integerValue];
                //CUP
                if ((begin >= 622126 && begin <= 622925) && (16 != length))
                {
                    result = FALSE;                
                }
                //other
                else 
                {
                    result = TRUE;
                }
            }
        }
        if (result) 
        {
            NSInteger digitValue;
            NSInteger checkSum = 0;
            NSInteger index = 0; 
            NSInteger leftIndex;
            //even length,odd index 
            if (0 == length%2) 
            {
                index = 0;
                leftIndex = 1;
            }
            //odd length,even index         
            else 
            {
                index = 1;  
                leftIndex = 0;
            }
            while (index < length) 
            {
                digitValue = [[value substringWithRange:NSMakeRange(index,1)] integerValue];            
                digitValue = digitValue*2;
                if (digitValue >= 10) 
                {
                    checkSum += digitValue/10 + digitValue%10;
                }
                else
                {
                    checkSum += digitValue;
                }
                digitValue = [[value substringWithRange:NSMakeRange(leftIndex,1)] integerValue];                        
                checkSum += digitValue;    
                index += 2;
                leftIndex += 2;            
            }
            result = (0 == checkSum%10) ? TRUE:FALSE;
        }        
    }
    else
    {
        result = FALSE;
    }
    return result;
}
+ (BOOL) isValidBirthday:(Nsstring*)birthday
{
    BOOL result = FALSE;
    if (birthday && 8 == [birthday length]) 
    {
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"yyyyMMdd"];
        NSDate *date = [formatter dateFromString:birthday];
        [formatter release];
        if (date)
        {
            result = TRUE;
        }
    }
    return result;
}
+ (BOOL) isChinaUnicomPhoneNumber:(Nsstring*) phonenumber
{
    /**
     * 手机号码
     * 移动:134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
     * 联通:130,131,132,152,155,156,185,186
     * 电信:133,1349,153,180,189
     */
//    Nsstring * MOBILE = @"^1(3[0-9]|5[0-35-9]|8[025-9])\\d{8}$";
    /**
     10         * 中国移动:China Mobile
     11         * 134[0-8],188
     12         */
//    Nsstring * CM = @"^1(34[0-8]|(3[5-9]|5[017-9]|8[278])\\d)\\d{7}$";
//    /**
//     15         * 中国联通:China Unicom
//     16         * 130,186
//     17         */
    Nsstring * CU = @"^1(3[0-2]|5[256]|8[56])\\d{8}$";
//    /**
//     20         * 中国电信:China Telecom
//     21         * 133,189
//     22         */
//    Nsstring * CT = @"^1((33|53|8[09])[0-9]|349)\\d{7}$";
//    /**
//     25         * 大陆地区固话及小灵通
//     26         * 区号:010,020,021,022,023,024,025,027,028,029
//     27         * 号码:七位或八位
//     28         */
//    Nsstring * PHS = @"^0(10|2[0-5789]|\\d{3})\\d{7,8}$";
//    Nsstring * PHS1 = @"^0(10|2[0-5789]|\\d{3}-)\\d{7,8}$";

//    nspredicate *regextestmobile = [nspredicate predicateWithFormat:@"SELF MATCHES %@",MOBILE];
//    nspredicate *regextestcm = [nspredicate predicateWithFormat:@"SELF MATCHES %@",CM];
    nspredicate *regextestcu = [nspredicate predicateWithFormat:@"SELF MATCHES %@",CU];
//    nspredicate *regextestct = [nspredicate predicateWithFormat:@"SELF MATCHES %@",CT];
//    nspredicate *regextestphs = [nspredicate predicateWithFormat:@"SELF MATCHES %@",PHS];
//    nspredicate *regextestphs1 = [nspredicate predicateWithFormat:@"SELF MATCHES %@",PHS1];

    if (//([regextestmobile evaluateWithObject:phonenumber] == YES)|| 
//        ([regextestcm evaluateWithObject:phonenumber] == YES)||
//        ([regextestct evaluateWithObject:phonenumber] == YES)||
          ([regextestcu evaluateWithObject:phonenumber] == YES)
//        || ([regextestphs evaluateWithObject:phonenumber] == YES)
//        || ([regextestphs1 evaluateWithObject:phonenumber] == YES)
        )
    {
        return YES;
    }
    else 
    {
        return NO;
    }
}

+ (BOOL) isValid:(IdentifierType) type value:(Nsstring*) value 
{
    if (!value ||[[value stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] isEqualToString:@""]) {        
        return FALSE;
    }
    BOOL result = TRUE;
    switch (type) 
    {
        case IdentifierTypeZipCode:
            result = [IdentifierValidator isValidZipcode:value];
            break;
        case IdentifierTypeEmail:
//            result = [IdentifierValidator isValidEmail:value];
            result = [IdentifierValidator validateEmail:value];
            break;
        case IdentifierTypePhone:
            result = [IdentifierValidator isValidPhone:value];
            break;
        case IdentifierTypeUnicomPhone:
            result = [IdentifierValidator isChinaUnicomPhoneNumber:value];
            break;
        case IdentifierTypeQQ:
            result = [IdentifierValidator isValidNumber:value];
            break;
        case IdentifierTypeNumber:
            result = [IdentifierValidator isValidNumber:value];
            break;           
        case IdentifierTypestring:
            result = [IdentifierValidator isValidString:value];
            break;
        case IdentifierTypeIdentifier:
            result = [IdentifierValidator isValidIdentifier:value];            
            break;
        case IdentifierTypePassort:
            result = [IdentifierValidator isValidPassport:value];            
            break;            
        case IdentifierTypeCreditNumber:
            result = [IdentifierValidator isValidCreditNumber:value];
            break;
        case IdentifierTypeBirthday:
            result = [IdentifierValidator isValidBirthday:value];            
            break;
        default:
            break;
    }
    return result;
}
- (void) dealloc 
{
    [super dealloc];
}
@end

以上是编程之家(jb51.cc)为你收集整理的全部代码内容,希望文章能够帮你解决所遇到的程序开发问题。

如果觉得编程之家网站内容还不错,欢迎将编程之家网站推荐给程序员好友。

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...