sirisha
sirisha

Reputation: 171

How to validate textfield string in iphone?

i want to validate string for following condition

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

Upvotes: 0

Views: 977

Answers (2)

Naveen Thunga
Naveen Thunga

Reputation: 3675

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

Upvotes: 1

bal-iphone
bal-iphone

Reputation: 51

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

Upvotes: 1

Related Questions