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

后端 未结 4 1628
心在旅途
心在旅途 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

    Another alternate solution.

    You can do all the check using one regular expression.

    RegExp: ^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[$@$!%*?&])[A-Za-z\\d$@$!%*?&]{8,}
    

    You can use this as mention below:

    //Minimum 8 characters at least 1 Uppercase Alphabet, 1 Lowercase Alphabet, 1 Number and 1 Special Character:
    let regex = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[$@$!%*?&])[A-Za-z\\d$@$!%*?&]{8,}"
    let isMatched = NSPredicate(format:"SELF MATCHES %@", regex).evaluate(with: yourTextField.text)
    if(isMatched  == true) {
        // Do your stuff ..
    }  else {
        // Show Error Message.
    }
    

提交回复
热议问题