6

Possible Duplicate:
allow only alphanumeric characters for a UITextField

Is there a way of only letting the user input letters and numbers, no symbols, via the keyboard into a UITextField?

Community
  • 1
  • 1
daihovey
  • 3,485
  • 13
  • 66
  • 110

3 Answers3

10

Use this delegate methods.. as It works for me..

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if(textField == YOUR TEXT FIELD)
    {
        NSCharacterSet *invalidCharSet = [[NSCharacterSet characterSetWithCharactersInString:@"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"] invertedSet];
        NSString *filtered = [[string componentsSeparatedByCharactersInSet:invalidCharSet] componentsJoinedByString:@""];
        return [string isEqualToString:filtered];
    }
    else
        return YES;
}
Mehul Mistri
  • 15,037
  • 14
  • 70
  • 94
2
- (BOOL) textField: (UITextField *)theTextField shouldChangeCharactersInRange: (NSRange)range replacementString: (NSString *)string {    
  //return yes or no after comparing the characters
}
Ankit Srivastava
  • 12,347
  • 11
  • 63
  • 115
2

Try this:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
 {
   NSCharacterSet *nonNumberSet = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
        if(![string stringByTrimmingCharactersInSet:nonNumberSet].length)
        {
            return NO;
        }
   return YES;

}

Deviator
  • 688
  • 3
  • 7
  • This only works for decimals, no? – daihovey Apr 03 '12 at 05:48
  • 1
    Yes this code makes sure that the user does not enter any symbol as well as any character. You can modify it according to ur requirement by adding '||' int the if statement and comparing characters. – Deviator Apr 03 '12 at 05:51
  • looks like you can use NSCharacterSet alphanumericCharacterSet – daihovey Apr 03 '12 at 05:52
  • this code disables the backspace touches for uitextview (at least for my app). a better solution is using [string rangeOfCharacterFromSet:nonNumberSet].location != NSNotFound in the if statement. – emrahgunduz Aug 29 '12 at 06:36