diff --git a/JSONSchema/JSONSchema.swift b/JSONSchema/JSONSchema.swift index 3e502f9..0f63395 100644 --- a/JSONSchema/JSONSchema.swift +++ b/JSONSchema/JSONSchema.swift @@ -55,7 +55,7 @@ public struct Schema { self.schema = schema formats = [ - : + "ipv4": validateIPv4, ] } diff --git a/JSONSchema/Validators.swift b/JSONSchema/Validators.swift index 4874204..143621b 100644 --- a/JSONSchema/Validators.swift +++ b/JSONSchema/Validators.swift @@ -360,3 +360,19 @@ func validateDependencies(key:String, dependencies:[String])(value:AnyObject) -> return true } + +// MARK: Format + +func validateIPv4(value:AnyObject) -> ValidationResult { + if let ipv4 = value as? String { + if let expression = NSRegularExpression(pattern: "^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$", options: NSRegularExpressionOptions(0), error: nil) { + if expression.matchesInString(ipv4, options: NSMatchingOptions(0), range: NSMakeRange(0, ipv4.utf16Count)).count == 1 { + return .Valid + } + } + + return .Invalid(["'\(ipv4)' is not valid IPv4 address."]) + } + + return .Valid +}