Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Only Alphabet and whitespace allowed in UITextField Swift

Tags:

swift

swift3

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 .

like image 329
StevenTan Avatar asked Jun 07 '17 07:06

StevenTan


1 Answers

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 {

}
like image 162
Aravind A R Avatar answered Oct 01 '22 09:10

Aravind A R