本文介绍了如何在以下条件下验证密码?有什么功能吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  1. 它必须有一个大写字母.
  2. 它必须至少包含一个数字.
  3. 它必须包含标点符号.
  4. 字符串中不能包含单词"password".
  5. 必须大于7个字符且小于31个字符.

示例

输入:"passWord123 !!!!"

Input: "passWord123!!!!"

输出:false

输入:"turkey90AAA ="

Input: "turkey90AAA="

输出:true

我尝试了以下代码,

func SimplePassword(_ str: String) -> String {

  let password = self.trimmingCharacters(in: CharacterSet.whitespaces)
    let passwordRegx = "^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&<>*~:`-]).{8,}$"
   let passwordCheck = NSPredicate(format: "SELF MATCHES %@",passwordRegx)
    return passwordCheck.evaluate(with: password)

  return str

}

推荐答案

这里是用于验证密码的非正则表达式变体,我认为它比正则表达式解决方案更易于阅读和维护.

Here is a non-regex variant for validating the password, I would argue that it is easier to read and maintain than a regular expression solution.

func isValid(password: String) -> Bool {
    return (8...30).contains(password.count) &&
        password.rangeOfCharacter(from: .uppercaseLetters) != nil &&
        password.rangeOfCharacter(from: .decimalDigits) != nil &&
        password.rangeOfCharacter(from: .punctuationCharacters) != nil &&
        !password.lowercased().contains("password")
}

请注意,在您的示例中,您说"turkey90AAA =应该返回true,但是'='不是标点符号,因此上面的代码将不接受它.相反,此字符是一个符号,因此,如果要包含它,则还要对 .symbols 字符集 password.rangeOfCharacter(from:.symbols)!= nil

Note that in your example you say that "turkey90AAA=" should return true but '=' is not a punctuation mark so the above code will not accept it. Instead this character is a symbol so if you want to include it then also add a check against the .symbols character set, password.rangeOfCharacter(from: .symbols) != nil

这篇关于如何在以下条件下验证密码?有什么功能吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 18:25