Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to restrict certain characters in UITextField in Swift?

I am creating a trivia application that asks for a username on start up. I'd like to make it impossible to use characters such as #$@!^& etc (also including "space"). I took a look at this post here but it is written entirely in Objective-C. Thanks in advance.

like image 633
Dylan Ireland Avatar asked Apr 28 '16 21:04

Dylan Ireland


People also ask

How do I restrict UITextField to take only numbers in Swift?

Method 1: Changing the Text Field Type from storyboard. Select the text field that you want to restrict to numeric input. Go to its attribute inspector. Select the keyboard type and choose number pad from there.

How do I remove special characters from a string in Swift?

Swift String – Remove Specific Characters 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.

How do you make a text field Uneditable in Swift?

Set the Boolean variable to false, which enables editing in the text field. When someone taps the Done button, isEditing becomes false. Set the Boolean variable to true, which disables editing in the text field.


4 Answers

Swift 4 iOS 11.2.x based on using an extension, tests to see if a string is a valid hex number in this example.

extension String {

var containsValidCharacter: Bool {
    guard self != "" else { return true }
    let hexSet = CharacterSet(charactersIn: "1234567890ABCDEFabcdef")
    let newSet = CharacterSet(charactersIn: self)
    return hexSet.isSuperset(of: newSet)
  }
}

You use it like with the UITextFieldDelegate.

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    return (string.containsValidCharacter)
}

Although I read in an earlier post that CharacterSets do not support characters that are composed of more than one Unicode.Scalar; so use with caution I guess.

like image 98
user3069232 Avatar answered Sep 18 '22 22:09

user3069232


Since you're explicitly asking for Swift, I've translated the top asnwer in the linked question.

let notAllowedCharacters = " ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_.";

func textField(
    textField: UITextField,
    shouldChangeCharactersInRange range: NSRange,
    replacementString string: String)
    -> Bool
{
    let set = NSCharacterSet(charactersInString: notAllowedCharacters);
    let inverted = set.invertedSet;

    let filtered = string
        .componentsSeparatedByCharactersInSet(inverted)
        .joinWithSeparator("");
    return filtered != string;

}
like image 34
Evdzhan Mustafa Avatar answered Sep 18 '22 22:09

Evdzhan Mustafa


internal func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool{
     if let text = string{
           if text == "#" || text == "$" || text == "!"{ \\and so on
              return false
           }
     }
     return true
}
like image 32
Andrew McKinley Avatar answered Sep 17 '22 22:09

Andrew McKinley


Swift 2.3

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {

        let characters = ["#", "$", "!", "&","@"]
        for character in characters{
            if string == character{
                print("This characters are not allowed")
                return false
            }
        }
}
like image 33
fs_tigre Avatar answered Sep 21 '22 22:09

fs_tigre