2013-08-01 45 views
0

我需要驗證用戶在我的應用中登錄時使用的用戶名。例如:用簡單的方法驗證iOS上的用戶名

彼得$ @是無效的,但 peter123有效

如果用戶名包含#$%&「* + -/=^_`{|}〜@ ,;!?在他的名字,alertView應該出現通知用戶

我必須比較這樣的字符串嗎?

-(BOOL) checkIfUsernameValidation{ 
    NSString *_username = playerName.text; 
    NSString *expression = @".!#$%&'*+-/=?^_`{|}[email protected],;"; 

    if(![_username compare:expression]){ 
     return YES; 
    } 
    else 
     return NO; 
} 

感謝

+0

也許這線程將幫助http://stackoverflow.com/questions/16866879/string-contains-letters – Arbitur

回答

4

一種方法是使用NSCharacterSet

例如,創建一個字符集所有你允許的字符,然後看看你的文本字段,並使用這樣的:

NSCharacterSet * characterSetFromTextField = [NSCharacterSet characterSetWithCharactersInString: yourTextField]; 
if([[NSCharacterSet alphanumericCharacterSet] isSupersetOfSet: characterSetFromTextField] == NO) 
{ 
    NSLog(@"there are bogus characters here, throw up a UIAlert at this point"); 
    return; 
} 

我用alphanumericCharacterSet,但是你可以很容易地使用"characterSetWithCharactersInString"創建您自己的所有允許字符的字符集。

+0

感謝了很多人!它工作出色。 – Vergmort

0

假設你正在使用UITextField,你可以作爲代表和實現textField:shouldChangeCharactersInRange:replacementString:然後用rangeOfCharacterFromSet:從你的不被允許的字符字符串創建的字符集。如果找到有效的範圍,那麼只要用戶鍵入無效字符,您就可以顯示警報。

0
-(BOOL) checkIfUsernameValidation{ 
    NSString *_username = playerName.text; 

    NSCharacterSet * set = [[NSCharacterSet characterSetWithCharactersInString:@".!#$%&'*+-/=?^_`{|}[email protected],;"] invertedSet]; 

    if ([_username rangeOfCharacterFromSet:set].location != NSNotFound){ 
     return YES; 
    } 
    else 
     return NO; 
    } 
} 
0
- (BOOL)isValidUsername { 
    NSCharacterSet *set = [NSCharacterSet 
     characterSetWithCharactersInString:@".!#$%&'*+-/=?^_`{|}[email protected],;"]; 

    return [self rangeOfCharacterFromSet:set].location == NSNotFound; 
}