p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px "PingFang SC" }
p.p2 { margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px "PingFang SC"; min-height: 17.0px }
一、本篇文章写作目的
我们项目中经常用到的有:
验证手机号码、
验证邮箱格式、
验证是否为中文、
验证网址、
验证是否含有非法字符、
判断密码6-16位同时包含数字和字母、
身份证的验证。
我先将此功能代码记录下来,方便大家传阅,希望对网友能够有所帮助。
提示:这方面的网上资源还是比较全的,可以自行搜索。举例:iOS 手机号码判断 正则表达式
二、具体内容
// 验证手机号码 + (BOOL)validateUserPhone:(NSString *)str { NSString *patternStr = [NSString stringWithFormat:@"^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(16[6])|(17[0,1,3,5-8])|(18[0-9])|(19[8,9]))\\d{8}$"]; NSRegularExpression *regularexpression = [[NSRegularExpression alloc] initWithPattern:patternStr options:NSRegularExpressionCaseInsensitive error:nil]; NSUInteger numberofMatch = [regularexpression numberOfMatchesInString:str options:NSMatchingReportProgress range:NSMakeRange(0, str.length)]; if(numberofMatch > 0) {return YES; }return NO; }
// 校验Email,带有域名验证 + (BOOL)validateEmail:(NSString *)_text { NSString *Regex=@"[0-9a-z._%+-][email protected][0-9a-z._]+\\.[a-z]{2,4}"; NSPredicate *emailTest=[NSPredicate predicateWithFormat:@"SELF MATCHES %@",Regex]; return [emailTest evaluateWithObject:_text]; }
// 是否为中文 + (BOOL)isChinese{ NSString *match=@"(^[\u4e00-\u9fa5]+$)"; NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF matches %@", match]; return [predicate evaluateWithObject:self]; }
// 是否是网址 + (BOOL)checkUrl:(id)_strInput { NSString *_strRegex = @"^(http|https|ftp)://[a-zA-Z0-9]+[.][a-zA-Z0-9]+([.][a-zA-Z0-9]+){0,1}(/[a-zA-Z0-9-_.+=?&%]*)*$"; NSPredicate* _predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",_strRegex]; if ([_predicate evaluateWithObject:_strInput]) { return YES; }else{ return NO; } }
// 是否有非法字符 + (BOOL)isHaveIllegalChar:(NSString *)str { NSCharacterSet *doNotWant = [NSCharacterSet characterSetWithCharactersInString:@"[]{}(#%-*+=_)\\|~(<>$%^&*)_+ "]; NSRange range = [str rangeOfCharacterFromSet:doNotWant]; return range.location<str.length; }
// 判断密码6-16位且同时包含数字和字母 +(BOOL)judgePassWordLegal:(NSString *)pass{ BOOL result = false; if ([pass length] >= 6){ // 判断长度大于6位后再接着判断是否同时包含数字和字母 NSString * regex = @"^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$"; NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex]; result = [pred evaluateWithObject:pass]; } return result; }
// 身份证号 + (BOOL) validateIdentityCard:(NSString *)identityCard { BOOL flag; if (identityCard.length <= 0) { flag = NO; return flag; } NSString *regex2 = @"^(\\d{14}|\\d{17})(\\d|[xX])$"; NSPredicate *identityCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex2]; return [identityCardPredicate evaluateWithObject:identityCard]; }
原文地址:https://www.cnblogs.com/cchHers/p/8608930.html
时间: 2024-10-05 02:02:20