Only Alphabet and whitespace allowed in UITextField Swift

pattern: ".*[^A-Za-z0-9 ].*" its allow to enter characters, numbers, or space(" ")

pattern: ".*[^A-Za-z ].*" its allow to enter characters, or space(" ")

pattern: ".*[^A-Za-z].*" its allow to enter only characters

Example below:

extension [YourViewController]: UITextFieldDelegate
{
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
                do {
                    let regex = try NSRegularExpression(pattern: ".*[^A-Za-z0-9 ].*", options: [])
                    if regex.firstMatch(in: string, options: [], range: NSMakeRange(0, string.count)) != nil {
                        return false
                    }
                }
                catch {
                    print("ERROR")
                }
            return true
    }
}

The easiest way will be to add new line to the character set like

let set = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLKMNOPQRSTUVWXYZ ")

i.e, adding white space character at the end of the included character set" "

Rather than hardcoding you can use regular expression like

   do {
    let regex = try NSRegularExpression(pattern: ".*[^A-Za-z ].*", options: [])
    if regex.firstMatch(in: nameValue, options: [], range: NSMakeRange(0, nameValue.characters.count)) != nil {
         self.showAlert(message: "Must not contain Number in Name")

    } else {

    }
}
catch {

}

Tags:

Swift

Swift3