0

I am making a sign-in/up function on Swift. I am trying to validate a password using regex. The passwords have the following requirements

  • At least 7 characters long
  • At least one uppercase letter
  • At least one number

This is the validation regex I was using: "^(?=.[A-Z])(?=.[0-9]){7}$"

And this is my code

let passwordTest = NSPredicate(format: "SELF MATCHES %@", "^(?=.[A-Z])(?=.[0-9]){7}$")

Whenever I try to log in with a password that meets these requirements (eg. Greatpass13), Xcode gives me an error saying

Thread 1: "Can't do regex matching, reason: (Can't open pattern U_REGEX_RULE_SYNTAX (string Greatpass13, pattern ^(?=.[A-Z])(?=.[0-9]){7}$, case 0, canon 0))"

3 Answers 3

1
(?=^.{7,}$)(?=^.*[A-Z].*$)(?=^.*\d.*$).*

Short Explanation

  • (?=^.{7,}$) At least 7 characters long
  • (?=^.*[A-Z].*$) At least one uppercase letter
  • (?=^.*\d.*$) At least one number
  • .* Match the string that contains all assertions

See the regex demo

Swift Example

let phonePattern = #"(?=^.{7,}$)(?=^.*[A-Z].*$)(?=^.*\d.*$).*"#

func isValid(password: String) -> Bool {
    return password.range(
        of: phonePattern,
        options: .regularExpression
    ) != nil
}

print(isValid(password: "Pass1"))       // false
print(isValid(password: "Pass23word"))  // true
print(isValid(password: "23password"))  // false
print(isValid(password: "Greatpass13")) // true
Sign up to request clarification or add additional context in comments.

Comments

0

you forgot to add dot before counter 7

func isValidPassword() -> Bool {
        let password = self.trimmingCharacters(in: CharacterSet.whitespaces)
        let passwordRegx = "^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9]).{7}$"
        let passwordCheck = NSPredicate(format: "SELF MATCHES %@",passwordRegx)
        return passwordCheck.evaluate(with: password)
 }

at least one uppercase,

at least one digit

at least one lowercase

min 7 characters total

Comments

0

Here is the updated regex based on yours.

let passwordRegx = "^(?=.*?[A-Z])(?=.*?[0-9]).{7,}$"
let passwordPredicate = NSPredicate(format: "SELF MATCHES %@",passwordRegx)

Also you need to add {7,} at the end otherwise it will only match for 7 characters and not more than that.

You can test your regex at: https://regex101.com/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.