Skip to content

Commit 50c180b

Browse files
janrose-gcxkylef
authored andcommitted
feat: Support uri format validation
1 parent 28fedb8 commit 50c180b

File tree

3 files changed

+25
-0
lines changed

3 files changed

+25
-0
lines changed

CHANGELOG.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,10 @@
66

77
- `ValidationResult.Valid` was renamed to `ValidationResult.valid`.
88

9+
### Enhancements
10+
11+
- `uri` format is now validated.
12+
913

1014
## 0.3.0
1115

Sources/JSONSchema.swift

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,7 @@ public struct Schema {
6161
formats = [
6262
"ipv4": validateIPv4,
6363
"ipv6": validateIPv6,
64+
"uri": validateURI,
6465
]
6566
}
6667

Sources/Validators.swift

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -423,3 +423,23 @@ func validateIPv6(_ value:Any) -> ValidationResult {
423423

424424
return .valid
425425
}
426+
427+
func validateURI(_ value:Any) -> ValidationResult {
428+
if let uri = value as? String {
429+
// Using the regex from http://blog.dieweltistgarnichtso.net/constructing-a-regular-expression-that-matches-uris
430+
431+
if let expression = try? NSRegularExpression(pattern: "((?<=\\()[A-Za-z][A-Za-z0-9\\+\\.\\-]*:([A-Za-z0-9\\.\\-_~:/\\?#\\[\\]@!\\$&'\\(\\)\\*\\+,;=]|%[A-Fa-f0-9]{2})+(?=\\)))|([A-Za-z][A-Za-z0-9\\+\\.\\-]*:([A-Za-z0-9\\.\\-_~:/\\?#\\[\\]@!\\$&'\\(\\)\\*\\+,;=]|%[A-Fa-f0-9]{2})+)", options: NSRegularExpression.Options(rawValue: 0)) {
432+
let result = expression.matches(in: uri, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSMakeRange(0, uri.characters.count))
433+
if result.count == 1 {
434+
let foundRange = result[0].range
435+
if foundRange.location == 0 && foundRange.length == uri.characters.count {
436+
return .valid
437+
}
438+
}
439+
}
440+
441+
return .invalid(["'\(uri)' is not a valid URI."])
442+
}
443+
444+
return .valid
445+
}

0 commit comments

Comments
 (0)