55

I want to implement a regex validaton for passwords in Swift? I have tried the following regex, but not successful

([(0-9)(A-Z)(!@#$%ˆ&*+-=<>)]+)([a-z]*){6,15}

My requirement is as follows: Password must be more than 6 characters, with at least one capital, numeric or special character

2
  • 3
    Why limit the special characters and password length? That just forces passwords to be less secure and irritates anyone who uses generated passwords. Commented Sep 2, 2016 at 6:31
  • 1
    I have that requirement, thats why Commented Sep 2, 2016 at 6:33

6 Answers 6

129

You can use Regex for check your password strength

^(?=.*[A-Z].*[A-Z])(?=.*[!@#$&*])(?=.*[0-9].*[0-9])(?=.*[a-z].*[a-z].*[a-z]).{8}$

Regex Explanation : -

^                         Start anchor
(?=.*[A-Z].*[A-Z])        Ensure string has two uppercase letters.
(?=.*[!@#$&*])            Ensure string has one special case letter.
(?=.*[0-9].*[0-9])        Ensure string has two digits.
(?=.*[a-z].*[a-z].*[a-z]) Ensure string has three lowercase letters.
.{8}                      Ensure string is of length 8.
$                         End anchor.

Source - Rublar Link

Sign up to request clarification or add additional context in comments.

2 Comments

The explanation is helpful to better understand and hence create desired regular expression.
nice explanation
93

try with this one for Password must be more than 6 characters, with at least one capital, numeric or special character

^.*(?=.{6,})(?=.*[A-Z])(?=.*[a-zA-Z])(?=.*\\d)|(?=.*[!#$%&? "]).*$

^ assert position at start of the string
.* matches any character (except newline)
Quantifier: * Between zero and unlimited times, as many times as possible, giving back as needed [greedy]
(?=.{6,}) Positive Lookahead - Assert that the regex below can be matched
.{6,} matches any character (except newline)
Quantifier: {6,} Between 6 and unlimited times, as many times as possible, giving back as needed [greedy]
(?=.*[A-Z]) Positive Lookahead - Assert that the regex below can be matched
.* matches any character (except newline)
Quantifier: * Between zero and unlimited times, as many times as possible, giving back as needed [greedy]
[A-Z] match a single character present in the list below
A-Z a single character in the range between A and Z (case sensitive)
(?=.*[a-zA-Z]) Positive Lookahead - Assert that the regex below can be matched
.* matches any character (except newline)
Quantifier: * Between zero and unlimited times, as many times as possible, giving back as needed [greedy]
[a-zA-Z] match a single character present in the list below
a-z a single character in the range between a and z (case sensitive)
A-Z a single character in the range between A and Z (case sensitive)
(?=.*\\d) Positive Lookahead - Assert that the regex below can be matched
.* matches any character (except newline)
Quantifier: * Between zero and unlimited times, as many times as possible, giving back as needed [greedy]
\d match a digit [0-9]
2nd Alternative: (?=.*[!#$%&? "]).*$
(?=.*[!#$%&? "]) Positive Lookahead - Assert that the regex below can be matched
.* matches any character (except newline)
Quantifier: * Between zero and unlimited times, as many times as possible, giving back as needed [greedy]
[!#$%&? "] match a single character present in the list below
!#$%&? " a single character in the list !#$%&? " literally (case sensitive)
.* matches any character (except newline)
Quantifier: * Between zero and unlimited times, as many times as possible, giving back as needed [greedy]
$ assert position at end of the string

https://regex101.com/#javascript

more this you can try ....

Minimum 8 characters at least 1 Alphabet and 1 Number:

"^(?=.*[A-Za-z])(?=.*\\d)[A-Za-z\\d]{8,}$"

Minimum 8 characters at least 1 Alphabet, 1 Number and 1 Special Character:

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

Minimum 8 characters at least 1 Uppercase Alphabet, 1 Lowercase Alphabet and 1 Number:

"^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)[a-zA-Z\\d]{8,}$"

Minimum 8 characters at least 1 Uppercase Alphabet, 1 Lowercase Alphabet, 1 Number and 1 Special Character:

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

Minimum 8 and Maximum 10 characters at least 1 Uppercase Alphabet, 1 Lowercase Alphabet, 1 Number and 1 Special Character:

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

8 Comments

What about this : Password must be more than 6 characters, with at least one capital, numeric or special character
^.*(?=.{6,})(?=.*[A-Z])(?=.*[a-zA-Z])(?=.*\d)|(?=.*[!#$%&? "]).*$
What is the significance of string in square brackets before range in all these regex? We don't provide these square brackets in javascript regex.
+~`^-_= are also special characters but are not being entertained in these expressions as Alphanumeric characters
For your use case 4 (min 8, 1 upper, 1 lower, 1 number and 1 special) you have an errant d in the special characters set. This allows something like "Password1" to work. Removing that d corrects the issue. (?=.*[$@$!%*?&#])
|
32
public func isValidPassword() -> Bool {
    let passwordRegex = "^(?=.*\\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z!@#$%^&*()\\-_=+{}|?>.<,:;~`’]{8,}$"
    return NSPredicate(format: "SELF MATCHES %@", passwordRegex).evaluate(with: self)
}

If you need a quick fix. This is validation for a password with regex. Copy/paste in helper or extension file and use it.

5 Comments

The - inside a character class creates a range, you should escape it. I have edited the answer.
It is more useful if you provide short info about above Regex.
@HardikThakkar You can always Google it bro!
@Html Tosin comment is for -Psajho Nub, not for you bro. With more details user who see answer can understand what will be the result of above answer.
@HtmlTosin I provide an answer that is working if you wont to fully understand, pls google everything about regex. Everything is self-explanatory except regex. Here is a link for more learning : regexr.com Tnx guys :)
12
func isValidPassword() -> Bool {
    // least one uppercase,
    // least one digit
    // least one lowercase
    // least one symbol
    //  min 8 characters total
    let password = self.trimmingCharacters(in: CharacterSet.whitespaces)
    let passwordRegx = "^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&<>*~:`-]).{8,}$"
    let passwordCheck = NSPredicate(format: "SELF MATCHES %@",passwordRegx)
    return passwordCheck.evaluate(with: password)

}

for which missing validation:

func getMissingValidation(str: String) -> [String] {
    var errors: [String] = []
    if(!NSPredicate(format:"SELF MATCHES %@", ".*[A-Z]+.*").evaluate(with: str)){
        errors.append("least one uppercase")
    }
    
    if(!NSPredicate(format:"SELF MATCHES %@", ".*[0-9]+.*").evaluate(with: str)){
        errors.append("least one digit")
    }

    if(!NSPredicate(format:"SELF MATCHES %@", ".*[!&^%$#@()/]+.*").evaluate(with: str)){
        errors.append("least one symbol")
    }
    
    if(!NSPredicate(format:"SELF MATCHES %@", ".*[a-z]+.*").evaluate(with: str)){
        errors.append("least one lowercase")
    }
    
    if(str.count < 8){
        errors.append("min 8 characters total")
    }
    return errors
}

3 Comments

Is there a way to know which validation is missing and return set error?
I need same validation but different cases, so that find which validation is missing
@XimenaFloresdelaTijera @PintuRajput added the getMissingValidation function
9

The regex is

(?:(?:(?=.*?[0-9])(?=.*?[-!@#$%&*ˆ+=_])|(?:(?=.*?[0-9])|(?=.*?[A-Z])|(?=.*?[-!@#$%&*ˆ+=_])))|(?=.*?[a-z])(?=.*?[0-9])(?=.*?[-!@#$%&*ˆ+=_]))[A-Za-z0-9-!@#$%&*ˆ+=_]{6,15}

Comments

3
func validpassword(mypassword : String) -> Bool 
    {    

        let passwordreg =  ("(?=.*[A-Z])(?=.*[0-9])(?=.*[a-z])(?=.*[@#$%^&*]).{8,}")
        let passwordtesting = NSPredicate(format: "SELF MATCHES %@", passwordreg)
        return passwordtesting.evaluate(with: mypassword)       
    }

 @IBOutlet weak var password_textfield: UITextField! //create a Password text field IBOutlet

@IBAction func login_btton(_ sender: UIButton) { //Click & Call to Login Button


let password = validpassword(mypassword: password_textfield.text!) //get text Field data & checked through the function


        if(password == false)
        {
             print("Valid Password")  //Use to Alert Msg Box 
        }
        else
        {
             print("Login Safe")     //Use to Alert Msg Box 
        }
    }
## Function Use to validation is password and confirm password is same, Password must have more then some characters , Password contain some special character , Password must one digit , Password must one uppercase letter ## 

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.