Issues relating to password authentication

I have a login system which authenticates the users password to check that it meets the following criteria:

  • 9 characters minimum
  • contains a capital character
  • contains a special character

Here’s my code which is run from my ‘SignUpViewController’

 // Check if the password is secure
    let cleanedPassword = passwordTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines)
    if Utilities.isPasswordValid(cleanedPassword) == false {
        let alert = UIAlertController(title: "Invalid Password", message: "Please make sure your password is at least 8 characters, contains a special character and a number.", preferredStyle: UIAlertController.Style.alert)

                // add an action (button)
                alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil))

                // show the alert
                self.present(alert, animated: true, completion: nil)
    return nil

And here is the code which is run from my ‘Utilities.ispasswordvalid’ file:

    static func isPasswordValid(_ password : String) -> Bool {
    let passwordTest = NSPredicate(format: "SELF MATCHES %@", "^(?=.*[a-z])(?=.*[$@$#!%*?&])[A-Za-z\\d$@$#!%*?&]{8,}")
    return passwordTest.evaluate(with: password)

This previously works, and creates a new user, however when I enter in the required details, the alert popup is displayed for around 1 second and then takes me to the correct view controller. Does anyone know why this alert displaying the ‘Invalid Password’ message appears for a short time, even though everything else works fine?

It doesn’t break anything, but is just quite annoying!!

In your sign up view controller why are you returning nil at the end?

It seems like it’s presenting and then goes away because your function is continuing on

Hi, I am returning nill at the end as I am using an ‘if loop’ to check the password to see if it is valid or not. When I comment out the ‘return nil’ it just displays the following error:

Missing return in a function expected to return 'String?'

You need to write your function in a different way.

func isValidPassword -> Bool
   let cleanedPassword = passwordTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines)
    if Utilities.isPasswordValid(cleanedPassword) == false { return false }
else { return true}

Then in your SignUpVC
Have something calling that function and then put the alert

if !isValidPassword()  {
 // put alertVC here

You need to put your password logic in one function (using the regex to check for a valid password.

Perfect thank you for your help! I’ve got it working now :slight_smile:

1 Like