您的位置:首页 > 移动开发 > IOS开发

iOS开发-正则表达式验证手机号

2016-03-31 12:49 483 查看
- (BOOL)isMobileNumber:(NSString *)mobileNum {
/*
手机号码
移动: 134[0-8], 135, 136, 137, 138, 139, 150, 151, 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}$";
/*
中国移动: China Mobile
移动: 134[0-8], 135, 136, 137, 138, 139, 150, 151, 158, 159, 182, 187, 188
*/

NSString * CM = @"^1(34[0-8]|(3[5-9]|5[017-9]|8[278])\\d)\\d{7}$";
/*
中国联通: China Unicom
联通: 130, 131, 132, 152, 155, 156, 185, 186
*/

NSString * CU = @"^1(3[0-2]|5[256]|8[56])\\d{8}$";
/*
中国电信: China Telecom
电信: 133, 1349, 153, 180, 189
*/

NSString * CT = @"^1((33|53|8[09])[0-9]|349)\\d{7}$";
/*
大陆地区固定电话及小灵通
区号: 010, 020, 021, 022, 023, 024, 025, 027, 028, 029
号码: 七位或八位
*/

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];

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

}


@interface ViewController : UIViewController
{
UITextField *textMobile;
}

@end


#import "MobileNumFormat.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];

UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(30, 200, 60, 25)];
label.text = @"手机号:";
[self.view addSubview:label];

textMobile = [[UITextField alloc] initWithFrame:CGRectMake(90, 200, 200, 25)];
textMobile.layer.borderColor = [UIColor blackColor].CGColor;
textMobile.layer.borderWidth = 1.0;
textMobile.layer.cornerRadius = 2.0;
[self.view addSubview:textMobile];

UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(80, 250, 200, 35)];
[btn setTitle:@"确  定" forState:UIControlStateNormal];
[btn setBackgroundColor:[UIColor grayColor]];
[btn addTarget:self action:@selector(btn:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn];
}

- (void)btn:(id)sender {
MobileNumFormat *mobile = [[MobileNumFormat alloc] init];

if ([mobile isMobileNumber:textMobile.text] == NO) {
UIAlertView *alter = [[UIAlertView alloc]initWithTitle:@"温馨提示"
message:@"手机号码格式错误"
delegate:self
cancelButtonTitle:nil
otherButtonTitles:@"确定", nil];
[alter show];
}

}

@end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: