Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to restrict special characters in UITextField in iPad?

In my iPad app. I have one UITextField. User would enter some value in that text field. This value has to be Alpha Numeric. I want to show an alert to the user if he/she enters any special character. How can I do it? What should be the condition for alert?

Any help would be highly appreciated.

Thanks and regards, PC

like image 435
Prateek Chaubey Avatar asked May 18 '12 13:05

Prateek Chaubey


2 Answers

Implement textField:shouldChangeCharactersInRange:replacementString: in the delegate, check the replacement string for special characters, and disallow the replacement if you detect any.

The easiest way to check for non-alphanumerics is as follows:

if ([replacementString rangeOfCharacterFromSet:[[NSCharacterSet alphanumericCharacterSet] invertedSet]].location != NSNotFound) {
    // There are non-alphanumeric characters in the replacement string
}
like image 66
Sergey Kalinichenko Avatar answered Nov 11 '22 15:11

Sergey Kalinichenko


You can do it as :-

#define ACCEPTABLE_CHARECTERS @" ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
   NSCharacterSet *acceptedInput = [NSCharacterSet characterSetWithCharactersInString:ACCEPTABLE_CHARECTERS];

   if (![[string componentsSeparatedByCharactersInSet:acceptedInput] count] > 1)
      return NO;
   else
      return YES;
}
like image 5
Maulik Avatar answered Nov 11 '22 17:11

Maulik