2012-08-01 59 views
0

驗證文本字段我試着用特殊字符來驗證文本字段,鍵盤退格鍵不工作時有特殊字符

但是,從鍵盤上按下刪除按鈕。文本提交的數據沒有刪除。

我用這個代碼來驗證文本字段,

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string 
{ 
     NSCharacterSet * invalidNumberSet = [NSCharacterSet characterSetWithCharactersInString:@"[email protected]#$%^&*()[]{}'\"<>:;|\\/?+=~`"]; 

    if([[string stringByTrimmingCharactersInSet:invalidNumberSet]isEqualToString:@""]) 
    { 
     return NO; 
    } 
    else 
    { 
     return YES; 
    } 
} 

請,建議我,我該怎麼辦呢?

+0

是要防止那些特殊字符或不 – 2012-08-01 11:39:56

回答

2

創建這樣的通用功能,實現你的功能,

-(BOOL)isNumeric:(NSString *)pTmpString 
{ 
    BOOL isValid = YES; 
    NSCharacterSet *myCharSet = [NSCharacterSet characterSetWithCharactersInString:@"[email protected]#$%^&*()[]{}'\"<>:;|\\/?+=~`"]; 
    for (int i = 0; i < [pTmpString length]; i++) 
    { 
     unichar c = [pTmpString characterAtIndex:i]; 
     if ([myCharSet characterIsMember:c]) 
      isValid = NO; 
    } 
    return isValid; 
} 

,並用它作爲

- (BOOL)textField:(UITextField *)theTextField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string 
{ 
    BOOL isValid = [self isNumeric:string];  
    return isValid; 
} 

這將不接受來自您的鍵盤特殊字符的文本框,雖然你按下那個字母從你的鍵盤。

如果你有那麼任何疑問告訴me..I將幫助你..

希望這將幫助你..

0

爲了防止這些特殊的詞,我建議這可能會幫助並沒有這麼多的選項,以防止這種類型的字符串相匹配的方式,我建議你這低於了一個。

if([string isEqualToString:@"_"] || [string isEqualToString:@"@"] || [string isEqualToString:@"#"] || [string isEqualToString:@"$"] || [string isEqualToString:@"%"] || [string isEqualToString:@"^"] || [string isEqualToString:@"&"] || [string isEqualToString:@"*"] || [string isEqualToString:@"("] || [string isEqualToString:@")"] || [string isEqualToString:@"["] || [string isEqualToString:@"]"] || [string isEqualToString:@"{"] || [string isEqualToString:@"'"] || [string isEqualToString:@"\""] || [string isEqualToString:@"\\"] || [string isEqualToString:@"<"] || [string isEqualToString:@">"]|| [string isEqualToString:@":"]|| [string isEqualToString:@";"]|| [string isEqualToString:@"|"]|| [string isEqualToString:@"/"]|| [string isEqualToString:@"?"]|| [string isEqualToString:@"+"] || [string isEqualToString:@"="]|| [string isEqualToString:@"~"] ) { 
     return NO; 
    }else{ 
     return YES; 
    } 

而另一種選擇是正則表達式。 希望這可以幫助你。