How do I check UITextField values for specific types of characters e.g. Letters or Number?

送分小仙女□ 提交于 2019-12-06 04:28:21

This is how I done it in the end.

    override func textFieldDidEndEditing(textField: UITextField) {

        let usernameField = self.signUpView.usernameField.text as NSString
        let alphaNumericSet = NSCharacterSet.alphanumericCharacterSet()
        let invalidCharacterSet = alphaNumericSet.invertedSet
        let rangeOfInvalidCharacters = usernameField.rangeOfCharacterFromSet(invalidCharacterSet)
        let userHasNameInvalidChars = rangeOfInvalidCharacters.location != NSNotFound

        if textField == self.signUpView.usernameField {

            if userHasNameInvalidChars {
                errorLabel.text = "Letters and numbers only please!"
                self.signUpView.signUpButton.enabled = false
                // do more error stuff here
            } else {
                self.signUpView.signUpButton.enabled = true
            }
         }
     }

Thanks to the blog post: http://toddgrooms.com/2014/06/18/unintuitive-swift/

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