如何检查特定类型字符的 UITextField 值,例如字母还是数字? [英] How do I check UITextField values for specific types of characters e.g. Letters or Number?

查看:26
本文介绍了如何检查特定类型字符的 UITextField 值,例如字母还是数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果 textField 中包含除字母、数字、破折号和空格以外的任何内容,我想要做的是在下面的 if 语句中将一些布尔值设置为 true.

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.

这是我检查长度的方式:

    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
    }

这个 if 语句在 UITextFieldDelegate 方法 textFielddidEndEditing 中.我有一种感觉,我必须使用某种形式的正则表达式来检查有效的电子邮件.

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.

是否有一些首选的方法可以做到这一点?在objective-c 中,我使用了 NSCharacterSet 但不确定如何在这里实现它.

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

感谢您的时间

推荐答案

我最后就是这样解决的.

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

感谢博文:http://toddgrooms.com/2014/06/18/unintuitive-swift/

这篇关于如何检查特定类型字符的 UITextField 值,例如字母还是数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆