0

Hello I need to enter mobile number with validation that mobile textfield range should be 10. And when textfield value ==10, i need to call a function when mobile textfield.text length becomes 10. My below code work fine but i need to press 1 more character (means 11) to call it. Please how i resolve it.

#define MAX_LENGTH 10

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (textField==user_mobile_txtField) 
   {


        if (textField.text.length >= MAX_LENGTH && range.length == 0)
        {

            if (textField.text.length==MAX_LENGTH) 
            {

                NSLog(@“Want to call Call method HERE ");

            }


            return NO; // return NO to not change text
        }


    }
     return YES;
}
Juan Catalan
  • 2,253
  • 1
  • 14
  • 23
9to5ios
  • 4,838
  • 2
  • 32
  • 59
  • Use the notification mentioned in [this question](http://stackoverflow.com/questions/7010547/uitextfield-text-change-event) instead. – Droppy Jun 02 '15 at 10:46

3 Answers3

2

shouldChangeCharactersInRange is called just before actual text has changed. If you want to perform an action after actual text has changed, you can try the approach below:

...
//start observing
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textHasChanged:) name:UITextFieldTextDidChangeNotification object:{your UITextField}];
...

- (void)textHasChanged:(NSNotification *)notification {
    UITextField *textField = [notification object];
    //check if textField.text.length >= 10
    //do stuff...
}
Mert Buran
  • 2,828
  • 2
  • 18
  • 32
2

You can get what the string will be after the characters are changed with the method stringByReplacingCharactersInRange:withString:

#define MAX_LENGTH 10

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (textField == user_mobile_txtField) {
        NSString *fullString = [textField.text stringByReplacingCharactersInRange:range withString:string];

        if (fullString.length >= MAX_LENGTH && range.length == 0) {
            if (fullString.length == MAX_LENGTH) {
                NSLog(@“Want to call Call method HERE ");
            }
            return NO; // return NO to not change text
        }
    }
    return YES;
}
keithbhunter
  • 11,822
  • 4
  • 32
  • 56
-1

Please try with below code -

#define MAX_LENGTH 10

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (textField==user_mobile_txtField) 
   {


        if (textField.text.length >= MAX_LENGTH )
        {

            if (textField.text.length==MAX_LENGTH) 
            {

                NSLog(@“Want to call Call method HERE ");

            }


            return NO; // return NO to not change text
        }


    }
     return YES;
}
Santu C
  • 2,528
  • 2
  • 10
  • 20