Only Alphabet and whitespace allowed in UITextField Swift

拥有回忆 提交于 2019-12-30 06:39:13

问题


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 .


回答1:


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 {

}



回答2:


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



回答3:


Use regex:

let regex = try! NSRegularExpression(pattern: "[a-zA-Z\\s]+", options: [])

You can match it like this:

let range = regex.rangeOfFirstMatch(in: string, options: [], range: NSRange(location: 0, length: string.characters.count))
return range.length == string.characters.count



回答4:


1st you have to inherit the UITextFieldDelegate class with you own class

class ViewController: UIViewController, UITextFieldDelegate {

2nd add an IBOutlet

@IBOutlet weak var firstName: UITextField!

3rd you have to assure this object is using

override func viewDidLoad() {
        super.viewDidLoad()
   firstName.delegate = self
}


func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    if textField == firstName {
                let allowedCharacters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
                let allowedCharacterSet = CharacterSet(charactersIn: allowedCharacters)
                let typedCharacterSet = CharacterSet(charactersIn: string)
                let alphabet = allowedCharacterSet.isSuperset(of: typedCharacterSet)
                return alphabet


      } else {
        return false
    }
  }



回答5:


All the above solutions are fine but only work for English Alphabet ([^A-Za-z ]). So this solution is not work for me because my app is developed for multiple language support. For this I write a solution and this is work for all language.

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

    let allowedCharacter = CharacterSet.letters
    let allowedCharacter1 = CharacterSet.whitespaces
    let characterSet = CharacterSet(charactersIn: string)
    return allowedCharacter.isSuperset(of: characterSet) || allowedCharacter1.isSuperset(of: characterSet)

}


来源:https://stackoverflow.com/questions/44405748/only-alphabet-and-whitespace-allowed-in-uitextfield-swift

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!