10

I want the keyboard for the UITextfield to only have a-z, no numbers, no special characters (!@$!@$@!#), and no caps. Basicly I am going for a keyboard with only the alphabet.

I was able to disable the space already. Anyone know how to disable numbers, special characters, and caps? A solution for any of these would be great.

Is the best solution to do the below for all the characters but I dont want?

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

    if (string == " ") {
        return false
    }

    if (string == "1") {
        return false
    }

    return true
}
Nischal Hada
  • 3,230
  • 3
  • 27
  • 57
gooberboobbutt
  • 797
  • 2
  • 8
  • 19

9 Answers9

12

An easiet way would be:

if let range = string.rangeOfCharacterFromSet(NSCharacterSet.letterCharacterSet())
    return true
}
else {
    return false
}
Imad Ali
  • 3,261
  • 1
  • 25
  • 33
Lennet
  • 413
  • 3
  • 10
  • with that is there a way to enable the backspace and disable caps (shift) – gooberboobbutt Jul 17 '15 at 16:59
  • 1
    you could reenable backspace support with the following OR (string == "" && range.length > 0) and for lowercase characters you should use lowercaseLetterCharacterSet() instead of letterCharacterSet() more information :http://nshipster.com/nscharacterset/ – Lennet Jul 17 '15 at 17:09
  • 1
    im new, how do i add the OR statement to that? – gooberboobbutt Jul 17 '15 at 17:18
  • 1
    http://stackoverflow.com/questions/26456587/swift-if-or-and-statement-like-python – Lennet Jul 17 '15 at 17:21
  • i did: if let range = string.rangeOfCharacterFromSet(NSCharacterSet.lowercaseLetterCharacterSet()) || (string == "" && range.length > 0) and it errors saying: optional type bool cannot be used as a boolean; test for != instead – gooberboobbutt Jul 17 '15 at 17:29
  • 1
    func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { if let letterRange = string.rangeOfCharacterFromSet(NSCharacterSet.lowercaseLetterCharacterSet()){ return true } else if !(string == "" && range.length > 0) { return false } return true } – Lennet Jul 17 '15 at 17:41
  • 1
    how can i allow space in it as well. like only alphabets and space and nothing else – Usama bin Attique Jan 25 '18 at 11:56
9

Update for those who wants to Allow Space, Caps & Backspace Only

Swift 4.x, Swift 5.x & up

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

    if range.location == 0 && string == " " { // prevent space on first character
        return false
    }

    if textField.text?.last == " " && string == " " { // allowed only single space
        return false
    }

    if string == " " { return true } // now allowing space between name

    if string.rangeOfCharacter(from: CharacterSet.letters.inverted) != nil {
        return false
    }

    return true
}
iAj
  • 3,787
  • 1
  • 31
  • 34
7

Swift 3 solution

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

     let characterSet = CharacterSet.letters

     if string.rangeOfCharacter(from: characterSet.inverted) != nil {
         return false      
     }
     return true
}
3

Swift 4.2 Code Allow only alphabets with allowing backspace if the user wants to remove wrong character

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    if string.rangeOfCharacter(from: .letters) != nil || string == ""{
        return true
    }else {
        return false
    }
}
AtulParmar
  • 4,358
  • 1
  • 24
  • 45
1

all the answers is working when user is not copy and paste in textfield for copy and paste to work use blow code

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

    let text = (textField.text! as NSString).replacingCharacters(in: range, with: string)
    let Regex = "[a-z A-Z ]+"
    let predicate = NSPredicate.init(format: "SELF MATCHES %@", Regex)
    if predicate.evaluate(with: text) || string == ""
    {
        return true
    }
    else
    {
        return false
    }

}
Devil Decoder
  • 966
  • 1
  • 10
  • 26
0
class ViewController: UIViewController,UITextFieldDelegate {  

     @IBOutlet var phoneTextField:UITextField!

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

     func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool
           {
                let textString = (textField.text! as NSString).replacingCharacters(in: range, with: string)

                if textField == self.phoneTextField  && string.characters.count > 0 {
                    let LettersOnly = NSCharacterSet.Letters
                    let strValid = LettersOnly.contains(UnicodeScalar.init(string)!)
                    return strValid && textString.characters.count <= 10
                }
                return true
            }
    }

Try this code
In above code is only allow 10 char in text field

Ramprasath Selvam
  • 3,868
  • 3
  • 25
  • 41
0
if isValidInput(Input: yourtextfieldOutletName.text!) == false {
    let alert = UIAlertController(title: "", message;"Name field accepts only alphabatics", preferredStyle: UIAlertControllerStyle.alert)
    alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil))

    self.present(alert, animated: true, completion: nil)
}

func isValidInput(Input:String) -> Bool {
    let myCharSet=CharacterSet(charactersIn:"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
    let output: String = Input.trimmingCharacters(in: myCharSet.inverted)
    let isValid: Bool = (Input == output)
    print("\(isValid)")

    return isValid
}
Anh Pham
  • 2,108
  • 9
  • 18
  • 29
0

Swift 3 with spaces

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    if string == " " { return true }
    if let _ = string.rangeOfCharacter(from: CharacterSet.letters){
        return true
    }
    return false
}
Dasoga
  • 5,489
  • 4
  • 33
  • 40
-1

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { let text = (textField.text! as NSString).replacingCharacters(in: range, with: string) let Regex = "[a-z A-Z ]+" let predicate = NSPredicate.init(format: "SELF MATCHES %@", Regex) if predicate.evaluate(with: text) || string == ""{ textField.text = textField.text?.replacingOccurrences(of: " ", with: "") return true } else{ return false } return true }

  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Dec 05 '22 at 17:22