开发者

How to validate textfield string in iphone?

i want to validate string for follo开发者_JAVA技巧wing condition

1.string contain characters only. 2.string don't allow space,enterkey and special characters.


To validate characters only you can use this code

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];
}


For condition 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];  

For Condition 2: You can use this delegate method

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
// checking for any whitespaces
if(([string rangeOfString:@" "].location != NSNotFound))
{
    return NO;
}
return YES;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜