how to check if an alphanumeric character is entered in text filed in iOS

831 views Asked by At

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

1

There are 1 answers

2
Buntylm On BEST ANSWER

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);
    }