Michel Ortega
Michel Ortega

Reputation: 13

Can't do regex matching on object on a UITextField with Swift

Validating a password entered by the user I´m getting the following error in Xcode:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Can't do regex matching on object Bopster.RegisterPresenter.'

This is the method used to validate the password entered as UITextField in the ViewController

func isValidPassword(password: String) -> Bool {
    let passwordRegex = "^(?=.*\\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z!@#$%^&*()\\-_=+{}|?>.<,:;~`’]{8,}$"
    debugPrint(passwordRegex)
    return NSPredicate(format: "SELF MATCHES %@", passwordRegex).evaluate(with: self)
}

here I declare a property that gets the boolean value from the regex.

let userPasswordChecked = isValidPassword(password: password)

then with a conditional I decide to move or show an error:

if userPasswordChecked {
    //  True, store it in COStorage.
    COStorage().savePassword(pass: password)
} else {
    //  False, message to user.
    let error = "La constraseña no es valida."
    self.view?.errorLoading(error: error)
}

I have tried with other patterns but so far it seems that the error is with the NSPredicate.

Upvotes: 1

Views: 586

Answers (1)

creeperspeak
creeperspeak

Reputation: 5523

Since you have declared your isValidPassword method in your RegisterPresenter class the self refers to the instance of RegisterPresenter.

You can solve your issue simply by changing the method from evaluate(with: self) to evaluate(with: password):

func isValidPassword(password: String) -> Bool {
    let passwordRegex = "^(?=.*\\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z!@#$%^&*()\\-_=+{}|?>.<,:;~`’]{8,}$"
    debugPrint(passwordRegex)
    return NSPredicate(format: "SELF MATCHES %@", passwordRegex).evaluate(with: password)
}

You want to evaluate with the password String being passed in, not with the RegisterPresenter.

Upvotes: 1

Related Questions