Pages

Subscribe:

Thursday, September 22, 2011

Telephone Number validation in a UITextField

// First you need to implement the UITextFieldDelegate in the .h file
// This validation will test, whether the number started with a '+' character or not & the number is not more than 19 digits.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSCharacterSet *invalidCharSet;
if(textField == txtTelephoneNumber)
{
invalidCharSet = [[NSCharacterSet characterSetWithCharactersInString:@" +0123456789"] invertedSet];
if([textField.text length] < 1)
{
if ([string characterAtIndex:0] != '+')
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error!" message:@"You must enter a valid telephone number. (Example: +8801913952792 ...)" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
[alert release];
return NO;
}
}
else
{
if ([textField.text characterAtIndex:0] != '+') {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error!" message:@"You must enter a valid telephone number. (Example: +01913952792 ...)" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
[alert release];
return NO;
}
}
if([textField.text length] > 19 && range.length == 0)
return NO;
}
else
{
invalidCharSet = [NSCharacterSet characterSetWithCharactersInString:@""];
//return [self validateEmail:string];
//invalidCharSet = [[NSCharacterSet characterSetWithCharactersInString:@""] invertedSet];
}

NSString *filtered = [[string componentsSeparatedByCharactersInSet:invalidCharSet] componentsJoinedByString:@""];

if(![string isEqualToString:filtered])
return NO;
else
return YES;
}

No comments:

Post a Comment