2014-02-10 31 views
-1

我創建了UITextField,我想對textfield(userName)進行驗證,以便只允許使用字符。如果用戶輸入除字母之外的其他任何內容(如數字或特殊字符),則不應出現,並且應該有通知顯示相同內容。在iOS中對UITextField進行驗證

回答

0

你可以試試這個:

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string 
    { 
     if(textField==YOUR_TEXTFIELD_NAME) 
     { 
      NSCharacterSet *myCharSet = [NSCharacterSet characterSetWithCharactersInString:@"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"]; 
      for (int i = 0; i < [string length]; i++) { 
       unichar c = [string characterAtIndex:i]; 
       if (![myCharSet characterIsMember:c]) { 
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Numbers not allowed" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil]; 
        [alert show]; 
        return NO; 
       } 

      } 

    } 
return YES; 
} 

請務必設置委託爲您文本框。

+0

感謝您的重播,但此代碼也允許 – user3291536

+0

1.您是否已將您的UITextField與IBOutlet連接? 2.您是否將UITextFieldDelegate設置爲您的文本字段? – GenieWanted

+0

謝謝我得到答案 – user3291536

-1
try this 

NSCharacterSet *blockedCharacters = [[NSCharacterSet alphanumericCharacterSet] invertedSet]; 

- (BOOL)textField:(UITextField *)field shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)characters 
{ 
    return ([characters rangeOfCharacterFromSet:blockedCharacters].location == NSNotFound); 
} 
-1
#define ACCEPTABLE_NUMBER @"1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" 

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string 
{ 

     NSCharacterSet *acceptedInput = [[NSCharacterSet characterSetWithCharactersInString:ACCEPTABLE_NUMBER]invertedSet]; 
     NSString *filtered = [[string componentsSeparatedByCharactersInSet:acceptedInput] componentsJoinedByString:@""]; 
     if ((![filtered isEqualToString:string])) 
      return NO; 
    } 

} 
3

限定ALPHA @ 「ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz」

- (BOOL)的TextField:(的UITextField *)的TextField shouldChangeCharactersInRange:(NSRange)範圍replacementString:(的NSString *)串{

NSCharacterSet *blockedCharacters = [[NSCharacterSet characterSetWithCharactersInString:ALPHA] invertedSet]; 

if (!([string rangeOfCharacterFromSet:blockedCharacters].location == NSNotFound)) { 
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Message" message:@"Only Alphabet allow." delegate:self cancelButtonTitle:@"Okay" otherButtonTitles:nil, nil]; 
    [alert show]; 
} 

return ([string rangeOfCharacterFromSet:blockedCharacters].location == NSNotFound); 

}