检查 UITextField 是否仅 characters/numbers

Check if a UITextField is characters/numbers only

我有这段代码....

let characterset = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-")
        if itemDescription.text!.rangeOfCharacter(from: characterset.inverted) != nil {
            print("string contains special characters")
            let message = MDCSnackbarMessage()
            message.text = "Numbers and letters only."
            MDCSnackbarManager.show(message)
            progressView.isHidden = true
            buttonSearchOutlet.isHidden = false
        }

无论我输入什么,我都会显示 snackbar。我希望这些是错误的

Hello
hello
hello1
hello-

我希望这是真的

Hello!
hello's
hello1@
hello$&@#

我做错了什么?

您可以简单地检查是否所有字符都满足条件,并检查具有有效字符的字符串是否包含这些字符。

extension StringProtocol {
    var isLetterDigitOrHyphen: Bool {
        allSatisfy("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-".contains)
    }
}

用法:

let str = "Hello"
if str.isLetterDigitOrHyphen {
    print("string is ok")
} else {
    print("string contains special characters")
}

"Hello".isLetterDigitOrHyphen  // true
"hello".isLetterDigitOrHyphen  // true
"hello1".isLetterDigitOrHyphen  // true
"hello-".isLetterDigitOrHyphen  // true

"Hello!".isLetterDigitOrHyphen  // false
"hello's".isLetterDigitOrHyphen  // false
"hello1@".isLetterDigitOrHyphen  // false
"hello$&@#".isLetterDigitOrHyphen  // false

如果您想使用正则表达式:

extension StringProtocol {
    var isLetterDigitOrHyphen: Bool {
        range(of:"^[a-zA-Z0-9-]{1,}$", options: .regularExpression) != nil
    }
}

或使用字符集:

extension StringProtocol {
    var isLetterDigitOrHyphen: Bool {
        unicodeScalars.allSatisfy(CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-").contains)
    }
}

当然,如果您愿意,您可以简单地否定结果:

extension String {
    static let validCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-"
}

extension StringProtocol {
    var isNotLetterDigitOrHyphen: Bool {
        !unicodeScalars.allSatisfy(CharacterSet(charactersIn: .validCharacters).contains)
    }
}