How to restrict special characters in UITextField on iPad?

In my iPad app. I have one UITextField. The user enters some value in this text box. This value must be Alpha Numeric. I want to show the user a warning if he or she falls into any special character. How can I do it? What should be the condition for warning?

Any help would be greatly appreciated.

Thank you and welcome, PC

+6
source share
2 answers

textField:shouldChangeCharactersInRange:replacementString: in the delegate, check the replacement string for special characters and prevent the replacement if you find any.

The easiest way to check for the absence of alphanumeric characters:

 if ([replacementString rangeOfCharacterFromSet:[[NSCharacterSet alphanumericCharacterSet] invertedSet]].location != NSNotFound) { // There are non-alphanumeric characters in the replacement string } 
+16
source

You can do it like: -

 #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; } 
+5
source

Source: https://habr.com/ru/post/916095/


All Articles