Check if a string contains at least a upperCase letter, a digit, or a special character in Swift?

后端 未结 4 1623
心在旅途
心在旅途 2021-01-31 05:18

I am trying to create a method that finds whether a string contains a number , Upper case letter and a special character using regular expression as below

 func         


        
4条回答
  •  孤独总比滥情好
    2021-01-31 05:25

    At least 1 Uppercase, 1 Lowercase, 1 Special Characters, 1 Number, and Total 8 Characters.

    To support all special characters listed in https://www.owasp.org/index.php/Password_special_characters

    !"#$%&'()*+,-./:;<=>?@[]^_`{|}~

    extension String {
        func isValidPassword() -> Bool {
            //let passwordRegex = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[ !\"\\\\#$%&'()*+,-./:;<=>?@\\[\\]^_`{|}~])[A-Za-z\\d !\"\\\\#$%&'()*+,-./:;<=>?@\\[\\]^_`{|}~]{8,}"
            //safe to escape all regex chars
            let passwordRegex = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[ !\"\\\\#$%&'\\(\\)\\*+,\\-\\./:;<=>?@\\[\\]^_`\\{|\\}~])[A-Za-z\\d !\"\\\\#$%&'\\(\\)\\*+,\\-\\./:;<=>?@\\[\\]^_`\\{|\\}~]{8,}"
            return NSPredicate(format: "SELF MATCHES %@", passwordRegex).evaluate(with: self)
        }
    }
    

提交回复
热议问题