我想验证以下条件的字符串
1.string仅包含字符。 2.string不允许空格,enterkey和特殊字符。
答案 0 :(得分:1)
要验证字符,您可以使用此代码
NSString *trimmed3 = [textfield.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
BOOL isNumeric = [trimmed3 length] >0 && [trimmed3 rangeOfCharacterFromSet:nonNumberSet].location== NSNotFound;
if (!isNumeric) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"oops"
message:@"Phone no should be numeric"
delegate: self
cancelButtonTitle: @"Continue"
otherButtonTitles: nil];
[alert show];
[alert release];
}
答案 1 :(得分:1)
条件1:
#define REG_EX_USERNAME_VALIDATION @"[a-zA-Z\\d]"
NSPredicate *userNameValidation = [ NSPredicate predicateWithFormat:@"SELF MATCHES %@", REG_EX_USERNAME_VALIDATION];
int retVal = [ userNameValidation evaluateWithObject:inPasskey];
对于条件2:您可以使用此委托方法
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
// checking for any whitespaces
if(([string rangeOfString:@" "].location != NSNotFound))
{
return NO;
}
return YES;
}