第一種使用正則表達(dá)式 判斷
//是否是純數(shù)字 + (BOOL)isNumText:(NSString *)str{ NSString * regex = @"(/^[0-9]*$/)"; NSPredicate * pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex]; BOOL isMatch = [pred evaluateWithObject:str]; if (isMatch) { return YES; }else{ return NO; } }
具體正則對(duì)不對(duì) 還需要大家來(lái)看以下
第二種 系統(tǒng)源生的
我推薦第二種
- (NSString *) trimming { return [self stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceCharacterSet]]; } //判斷是不是純數(shù)字 [NSCharacterSet decimalDigitCharacterSet]; if ([[textField.text stringByTrimmingCharactersInSet: [NSCharacterSet decimalDigitCharacterSet]]trimming].length >0) { DLog(@"不是純數(shù)字"); }else{ DLog(@"純數(shù)字!"); }
最近在做一個(gè)即時(shí)通訊的項(xiàng)目, 首先是注冊(cè)登錄界面, 項(xiàng)目需求是通過(guò)用戶(hù)輸入的手機(jī)號(hào)碼獲取一個(gè)4位數(shù)的驗(yàn)證碼來(lái)完成注冊(cè),那么, 問(wèn)題來(lái)了?
如何判斷用戶(hù)輸入的手機(jī)號(hào)碼是合法的正確的11位手機(jī)號(hào)碼呢?(這些簡(jiǎn)單的問(wèn)題就在前端判斷好了再post給后臺(tái) ,沒(méi)必要把各種沒(méi)用的數(shù)據(jù)都post給后臺(tái))
判斷手機(jī)號(hào)碼是否正確的方法很多,我是用正則表達(dá)式來(lái)完成匹配的,廢話(huà)不多說(shuō),直接上代碼:
//正則表達(dá)式匹配11位手機(jī)號(hào)碼 NSString *regex = @"^((13[0-9])|(15[^4,//D])|(18[0,0-9]))//d{8}$"; NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex]; BOOL isMatch = [pred evaluateWithObject:_telField.text]; if(isMatch) { //有效手機(jī)號(hào) }else//無(wú)效手機(jī)號(hào) { if (ios7) { UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:nil message:@"無(wú)效的手機(jī)號(hào)碼,請(qǐng)重新輸入..." delegate:self cancelButtonTitle:nil otherButtonTitles:@"確定", nil nil]; alertView.tag = 104; [alertView show]; }else { UIAlertController*alertController = [UIAlertController alertControllerWithTitle:nil message:@"無(wú)效的手機(jī)號(hào)碼,請(qǐng)重新輸入..." preferredStyle:UIAlertControllerStyleAlert]; UIAlertAction *otherAction = [UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleDefault handler:^(UIAlertAction*action) { [_telField selectAll:self]; }]; [alertController addAction:otherAction]; [self presentViewController:alertController animated:YES completion:nil]; } } }
聯(lián)通,移動(dòng)和電信每年都會(huì)添加新的號(hào)碼,所以匹配電話(huà)號(hào)碼的正則表達(dá)式也要年年更新.
^((13[0-9])|(15[^4,//D])|(18[0,0-9]))//d{8}$
這個(gè)正則表達(dá)式我測(cè)試過(guò)了還沒(méi)發(fā)現(xiàn)有匹配不了的號(hào)碼,在這里分享給大家用!
新聞熱點(diǎn)
疑難解答
圖片精選