Skip to content

Validate uri format #21

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Sources/JSONSchema.swift
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ public struct Schema {
formats = [
"ipv4": validateIPv4,
"ipv6": validateIPv6,
"uri": validateURI,
]
}

Expand Down
20 changes: 20 additions & 0 deletions Sources/Validators.swift
Original file line number Diff line number Diff line change
Expand Up @@ -423,3 +423,23 @@ func validateIPv6(_ value:Any) -> ValidationResult {

return .Valid
}

func validateURI(_ value:Any) -> ValidationResult {
if let uri = value as? String {
// Using the regex from http://blog.dieweltistgarnichtso.net/constructing-a-regular-expression-that-matches-uris

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)) {
let result = expression.matches(in: uri, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSMakeRange(0, uri.characters.count))
if result.count == 1 {
let foundRange = result[0].range
if foundRange.location == 0 && foundRange.length == uri.characters.count {
return .Valid
}
}
}

return .invalid(["'\(uri)' is not a valid URI."])
}

return .Valid
}