Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I restrict special characters in UITextField except dot and underscores?

How can I restrict special characters in a UITextField except dot and underscores?

I have tried the code snippet below, but without luck:

#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){             NSLog(@"not allowed");             return NO;         }         else{             return YES;         } } 
like image 772
Graham Bell Avatar asked Jan 28 '13 08:01

Graham Bell


People also ask

How do you avoid special characters in Swift?

To remove specific set of characters from a String in Swift, take these characters to be removed in a set, and call the removeAll(where:) method on this string str , with the predicate that if the specific characters contain this character in the String.


2 Answers

Try code block given below, it worked fine for me.

SWIFT 3.0

let ACCEPTABLE_CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_"  func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {     let cs = NSCharacterSet(charactersIn: ACCEPTABLE_CHARACTERS).inverted     let filtered = string.components(separatedBy: cs).joined(separator: "")      return (string == filtered) } 

Objective C

#define ACCEPTABLE_CHARACTERS @" ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_."  - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string  {       NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:ACCEPTABLE_CHARACTERS] invertedSet];        NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];        return [string isEqualToString:filtered]; } 

Hope it will work for you as well.

like image 168
Mrunal Avatar answered Oct 12 '22 22:10

Mrunal


Try this

NSCharacterSet  *set= [NSCharacterSet symbolCharacterSet]; if ([string rangeOfCharacterFromSet:[set invertedSet]].location == NSNotFound) {     // valid } else {     // invalid } 

you can make your own set with

NSCharacterSet  *set= [NSCharacterSet characterSetWithCharactersInString:@"<all your symbols you want to ignore>"]; 
like image 36
amar Avatar answered Oct 13 '22 00:10

amar