Search code examples
swiftswift3

Only Alphabet and whitespace allowed in UITextField Swift


I want to validate my textField that check only Alphabet & whitespace allowed, If number was given then it will return warning error.

//First I declare my value to variable
var nameValue: String = mainView.nameTextField.text!

//Then I declare this 
 let set = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLKMNOPQRSTUVWXYZ")        

//And this is the validation
if(nameValue.rangeOfCharacter(from: set.inverted) != nil ){
    self.showAlert(message: "Must not contain Number in Name")
   } else {
      //other code
   }


ex: nameValue : "abcd" it works, but 
if nameValue : "ab cd" whitespace included, it returns the showAlert message.

This code works but only for alphabets, What I need now is alphabets and a whitespace. and what I declare was a hardcode I guess. Maybe you guys have better code and options for this case.

Thank you .


Solution

  • 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 {
    
    }