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
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
}
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With