Skip to content

Instantly share code, notes, and snippets.

@sourleangchhean168
Last active April 23, 2024 04:29
Show Gist options
  • Save sourleangchhean168/ae77c0d95a29128e7a899f732197a233 to your computer and use it in GitHub Desktop.
Save sourleangchhean168/ae77c0d95a29128e7a899f732197a233 to your computer and use it in GitHub Desktop.
Check Valid Password
func isValidPassword(password: String) -> Bool {
// define validation rules here
let passwordRegEx = "(?=.*[A-Z])(?=.*[0-9])(?=.*[a-z]).{8,}"
let passwordPred = NSPredicate(format: "SELF MATCHES %@", passwordRegEx)
return passwordPred.evaluate(with: password)
}
@sourleangchhean168
Copy link
Author

How to use the isValidPassword(password:) function:

Example Usage:

  1. Checking Password Validity:

    let password = "MyPassword123"
    if isValidPassword(password: password) {
        print("Valid password")
    } else {
        print("Invalid password")
    }
  2. Validating User Input:

    let passwordTextField = UITextField()
    passwordTextField.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)
    
    @objc func textFieldDidChange(_ textField: UITextField) {
        if isValidPassword(password: textField.text ?? "") {
            textField.layer.borderColor = UIColor.green.cgColor
        } else {
            textField.layer.borderColor = UIColor.red.cgColor
        }
    }
  3. Displaying a Password Strength Indicator:

    let password = "MyPassword123"
    let strength = isValidPassword(password: password) ? "Strong" : "Weak"
    print("Password strength: \(strength)")

Explanation:

  • The isValidPassword(password:) function checks if a password meets certain validation rules, such as containing at least one uppercase letter, one lowercase letter, one digit, and being at least 8 characters long.
  • You can use the function to validate user input and provide feedback on password strength or validity.
  • In the example, the function is used to check the validity of a password entered in a text field, and to display a border color based on the password's validity.
  • The function can also be used to display a password strength indicator, such as "Strong", "Medium", or "Weak", based on the complexity of the password.

By using the isValidPassword(password:) function, you can ensure that passwords entered by users meet certain security requirements, and provide feedback on password strength or validity.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment