0

I am having a condition in which i want to check if there are any special characters entered in textfield.

If there are no special characters entered it should return YES. If a special character is entered in textfield a check is made to check if the special character is from a set characters. If the special entered is not from the set of special characters it should return NO.

This is my code:

NSCharacterSet *newrang = [[NSCharacterSet characterSetWithCharactersInString:@"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"] invertedSet];
    NSRange newrange = [pwd rangeOfCharacterFromSet:newrang];

    if (!newrange.length)
    {
        return YES;
    }
    else
    {
        NSCharacterSet* set =
        [[NSCharacterSet characterSetWithCharactersInString:@"!@#$%^&*"] invertedSet];
        NSRange checkrange = [pwd rangeOfCharacterFromSet:set];
        if (checkrange.location==NSNotFound)
        {
            NSLog(@"NO");
        }
        else
        {
            NSLog(@"YEs");
        }

            if ([pwd rangeOfCharacterFromSet:set].location == NSNotFound) {
                return NO;
            } else {
                return YES;
            }

    }

My problem is if i enter abc@_123 it is returning YES. Instead it should return NO coz an invalid special character:

"_"

is present .

Thanks

Mayur Prajapati
  • 5,454
  • 7
  • 41
  • 70
Rani
  • 3,333
  • 13
  • 48
  • 89

1 Answers1

2

Create NSCharacterSet of characters that you want to block like i created alphanumericCharacterSet invertedSet. Then validate every character with UITextFieldDelegate method textField:shouldChangeCharactersInRange:replacementString: as The text field calls this method whenever the user types a new character in the text field or deletes an existing character.

Review this hope this will help you

NSCharacterSet *blockCharacters = [[NSCharacterSet characterSetWithCharactersInString:@"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789@#"] invertedSet];    
- (BOOL)textField:(UITextField *)field shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)characters
    {
        return ([characters rangeOfCharacterFromSet:blockCharacters].location == NSNotFound);
    }
Buntylm
  • 7,345
  • 1
  • 31
  • 51
  • i don't want to avoid all special characters but specific ones. – Rani May 18 '14 at 13:22
  • which one you want to use only add with `blockCharacters` as i added `@#` at last simply add character you want to add this will resolved your problem. `abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789@#` – Buntylm May 18 '14 at 13:52