vin
vin

Reputation: 1258

how to eliminate the occurence of a certain character from a textfield and have it present only at the prefix

I have a UITextField that lets the user type in the phone number but i want to test the UITextField such that the user shouldnt enter a "+" anywhere else in the textfield apart from the prefix.

Is there any way i can test this condition? this is what i have done so far,please note this is the fourth textfield so i am using tag to distinguish it from other textfields

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



if (textField.tag==3)
{
    static NSCharacterSet *charSet = nil;
          if(!charSet) {
               charSet = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789+"] invertedSet];
          }
  NSRange location = [string rangeOfCharacterFromSet:charSet];
             return (location.location == NSNotFound);

// delete the characters backspace
    if ([string isEqualToString:@""])
    {
        return YES;
    }





   }
return YES;
 }

the above condition just allows only those numbers and "+" symbol thanks

Upvotes: 0

Views: 121

Answers (2)

vin
vin

Reputation: 1258

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


if (textField.tag==3)
{
    static NSCharacterSet *charSet = nil;
          if(!charSet) {
               charSet = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789+"] invertedSet];
          }
    if([textField.text length]>0){

        if([string isEqualToString:@"+"])
        {


            return NO;
        }
        else
        {
            NSRange location = [string rangeOfCharacterFromSet:charSet];
            return (location.location == NSNotFound);
            return YES;

        }
    }

    if ([string isEqualToString:@""])
    {
        return YES;
    }





}
return YES;
}

i changed the textfield.length to 0 coz i am inserting a "+" in the beginning automatically when textfieldShouldBeginEditing

Upvotes: 0

Balu
Balu

Reputation: 8460

try like this it wont take + anywhere else except first position ,

 - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
   if (textField.tag==3)
   {
        if([textField.text length]>1){
            if([string isEqualToString:@"+"])
            {
                return NO;
            }
            else 
            {
                return YES;
            }
        }
        return YES;
    }
}

Upvotes: 1

Related Questions