I’m trying to validate text length in textField. Here is what I try
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString *textLenght = [NSString stringWithFormat:@"%@", [textField text]];
if ([textLenght length] > 5)
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Message"
message:@"Too long"
delegate:self
cancelButtonTitle:@"OK"
otherButtonTitles:nil, nil];
[alert show];
[alert release];
return NO;
}
return YES;
}
This code works well. The alert box is displayed when I type more than 5 characters. The problem is that when I try to delete the last character of textfield the alert box is displayed again.
How to fix that ?
You have to create the actual string first
You check the length afterwards
And continue with the if (length) checking.
This way first creates the required string (also taking into consideration the backspaces).