Skip to content
This repository has been archived by the owner on Apr 20, 2024. It is now read-only.

Commit

Permalink
Format StrongPassword and allow to specify errorDescription
Browse files Browse the repository at this point in the history
  • Loading branch information
cweinberger committed Jun 30, 2018
1 parent 3f02395 commit 6a53e22
Showing 1 changed file with 15 additions and 11 deletions.
26 changes: 15 additions & 11 deletions Sources/Sugar/Validators/StrongPassword.swift
Original file line number Diff line number Diff line change
Expand Up @@ -22,26 +22,30 @@ public struct StrongPassword: Validator {
internal let minLength: Int
internal let minMatchingRegexes: Int
internal let regexes: [String]

public init(minLength: Int = 6,
regexes: [String] = standardRegexes,
minMatchingRegexes: Int = 3) {

internal var errorDescription: String?

public init(
minLength: Int = 6,
regexes: [String] = standardRegexes,
minMatchingRegexes: Int = 3,
errorDescription: String? = nil)
{
self.minLength = minLength
self.regexes = regexes
self.minMatchingRegexes = minMatchingRegexes
self.errorDescription = errorDescription
}

public func validate(_ input: String) throws {

let matchingRegexesCount = regexes
.reduce(0, {$0 + ((input.range(of: $1, options: .regularExpression) == nil) ? 0 : 1) })
.reduce(0, {
$0 + ((input.range(of: $1, options: .regularExpression) == nil) ? 0 : 1)
})

guard
input.count >= minLength,
matchingRegexesCount >= minMatchingRegexes
else {
throw error("Password is not strong enough. It must be be at least \(minLength) characters long and contain a number, a capital letter and a small letter.")
guard input.count >= minLength, matchingRegexesCount >= minMatchingRegexes else {
throw error(errorDescription ??
"Password is not strong enough. It must be be at least \(minLength) characters long and contain \(minMatchingRegexes) of these: a number, a capital letter, a small letter or a special character.")
}
}
}

0 comments on commit 6a53e22

Please sign in to comment.