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
Create
NSCharacterSet
of characters that you want to block like i createdalphanumericCharacterSet invertedSet
. Then validate every character withUITextFieldDelegate
methodtextField: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