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

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>"];

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.


NSString *Regex = @"[A-Za-z0-9^]*";

NSPredicate *TestResult = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", Regex];

[TestResult evaluateWithObject:@"YourTestString"];

Last return boolean value true/false

In Method

+ (BOOL) validateSpecialCharactor: (NSString *) text {
NSString *Regex = @"[A-Za-z0-9^]*";
NSPredicate *TestResult = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", Regex];
return [TestResult evaluateWithObject:text];
}

Swift 4

let RISTRICTED_CHARACTERS = "'*=+[]\\|;:'\",<>/?%"

UITextField delegate method:

func textField(_ textField: UITextField, shouldChangeCharactersIn _: NSRange, replacementString string: String) -> Bool {
    let set = CharacterSet(charactersIn: RISTRICTED_CHARACTERS)
    let inverted = set.inverted
    let filtered = string.components(separatedBy: inverted).joined(separator: "")
    return filtered != string
}