Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Added support for RegExp pattern Validation (#2856)
- Loading branch information
Showing
2 changed files
with
42 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
extension Validator where T == String { | ||
/// Validates whether a `String` matches a RegularExpression pattern | ||
public static func pattern(_ pattern: String) -> Validator<T> { | ||
.init { | ||
guard | ||
let range = $0.range(of: pattern, options: [.regularExpression]), | ||
range.lowerBound == $0.startIndex && range.upperBound == $0.endIndex | ||
else { | ||
return ValidatorResults.Pattern(isValidPattern: false, pattern: pattern) | ||
} | ||
return ValidatorResults.Pattern(isValidPattern: true, pattern: pattern) | ||
} | ||
} | ||
} | ||
|
||
extension ValidatorResults { | ||
/// `ValidatorResult` of a validator that validates whether a `String`matches a RegularExpression pattern | ||
public struct Pattern { | ||
public let isValidPattern: Bool | ||
public let pattern: String | ||
} | ||
} | ||
|
||
extension ValidatorResults.Pattern: ValidatorResult { | ||
public var isFailure: Bool { | ||
/// The input is valid for the pattern | ||
!self.isValidPattern | ||
} | ||
|
||
public var successDescription: String? { | ||
"is a valid pattern" | ||
} | ||
|
||
public var failureDescription: String? { | ||
"is not a valid pattern \(self.pattern)" | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters