2013-06-13 57 views
0

我想只允許a-z,0-9和_(下劃線),但它不能正常工作。NSPredicate驗證:a-z,0-9和下劃線

NSString *test = @"name_test09"; // should be valid 
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", @"[a-z0-9_]"]; 

if ([predicate evaluateWithObject:test] == NO) { 
    // not validated 
} else { 
    // validated 
} 

回答

-1

它應該是。

NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES[c] %@", @"[a-z][0-9]_"]; 

MY編輯:

NSString *s [email protected]"abcdefghijklmnopqrstuvwxyz1234567890_"; 
NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES[c] %@",s]; 

NSString *myRegex = @"[a-z0-9_]*"; 
NSPredicate *myTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", myRegex]; 
BOOL valid = [myTest evaluateWithObject: test]; 
if (valid) 
{ 
} 
else 
{ 
} 
+0

想你的代碼,但它仍返回不驗證。 –

+0

@ LucianoNascimento-嘗試我最新的更新,可能是*的錯誤,你忘記放在你的陣型:) – iPatel

+0

謝謝,它運作良好! –