1

I have created US Mobile format in UITextField, it allows US Format mobile number successfully (1-222-304-9876), but it also allow this type of numbers (1-234-56). how to restrict numbers, my UITextField allows only 14 characters. Please check my code... how to control that one.

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

NSString *text = mobileNo.text;

if(textField==mobileNo) {

    NSCharacterSet *myCharSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];

    for (int i = 0; i < [string length]; i--) {
        unichar c = [string characterAtIndex:i];
        if (![myCharSet characterIsMember:c]) {
            if (alertCheck == NO) {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Alphbets and Special characters not allowed" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
                [alert show];

                alertCheck = YES;
            }
            return NO;
        }

    }
}

NSString *acceptedcharacters = @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz123456789-/";
NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:acceptedcharacters] invertedSet];


if ([string isEqualToString:@"0"] && range.location == 0) {
    return NO;
}

const char * _char = [string cStringUsingEncoding:NSUTF8StringEncoding];
int isBackSpace = strcmp(_char, "\b");
if (isBackSpace == -8) {
    NSLog(@"deleted");
}
else {
    if (mobileNo.text.length == 1) {

        mobileNo.text = [NSString stringWithFormat:@"%@-",text];
        return YES;
    }
    if (mobileNo.text.length == 5) {

        mobileNo.text = [NSString stringWithFormat:@"%@-",text];
        return YES;
    }
    if (mobileNo.text.length == 9) {

        mobileNo.text = [NSString stringWithFormat:@"%@-",text];
        return YES;
    }
}
//   if (textField == self.phoneNumber_txtField) {
NSUInteger newLength = [mobileNo.text length] + [string length] - range.length;
return (newLength > 14) ? NO : YES;

//  }

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

//return [string isEqualToString:filtered];
 return (([string isEqualToString:filtered]) && (newLength <= 14));
}
Mustafa
  • 20,504
  • 42
  • 146
  • 209
Phanindra
  • 57
  • 1
  • 10

0 Answers0