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

筅森魡賤 提交于 2020-01-02 13:18:25

问题


What I want to do is set some boolean in the if statement below to true if anything other than letters, numbers, dashes and spaces is contained in the textField.

Then for an email field check for a valid email.

This is how I'm checking for length:

    if countElements(textField.text!) < 2 || countElements(textField.text) > 15 {
        errorLabel.text = "Name must have between 2 and 15 characters."
        self.signUpView.signUpButton.enabled = false
    } else {
        errorLabel.text = ""
        self.signUpView.signUpButton.enabled = true
    }

This if statement is inside the UITextFieldDelegate method textFielddidEndEditing. I have a feeling I'll have to use some form of regex to check for a valid email.

Would it make sense to use a regex to check a field only contains the characters I allow and return a boolean that'll tell me if the text field contains disallowed characters so I can then show an error message.

Is there some preferred way to do this? In objective-c I used NSCharacterSet but not sure how to implement that here.

Thanks for your time


回答1:


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/



来源:https://stackoverflow.com/questions/25651612/how-do-i-check-uitextfield-values-for-specific-types-of-characters-e-g-letters

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