|
| 1 | +import Foundation |
| 2 | + |
| 3 | + |
| 4 | +/* |
| 5 | +partial-time https://tools.ietf.org/html/rfc3339 |
| 6 | + |
| 7 | + time-hour = 2DIGIT ; 00-23 |
| 8 | + time-minute = 2DIGIT ; 00-59 |
| 9 | + time-second = 2DIGIT ; 00-58, 00-59, 00-60 based on leap second |
| 10 | + ; rules |
| 11 | + time-secfrac = "." 1*DIGIT |
| 12 | + time-numoffset = ("+" / "-") time-hour ":" time-minute |
| 13 | + time-offset = "Z" / time-numoffset |
| 14 | + |
| 15 | + partial-time = time-hour ":" time-minute ":" time-second |
| 16 | + [time-secfrac] |
| 17 | +*/ |
| 18 | + |
| 19 | + |
| 20 | +var timeExpression: NSRegularExpression = { |
| 21 | + let time = #""" |
| 22 | + (?x) |
| 23 | + ^ |
| 24 | + (?<hour>(([01]\d)|(2[0-3]))) |
| 25 | + : |
| 26 | + (?<minute>([0-5]\d)) |
| 27 | + : |
| 28 | + (?<second>(([0-5]\d)|(60))) |
| 29 | + (?<secfrac>\.\d+)? |
| 30 | + (?<offset> |
| 31 | + ( |
| 32 | + Z |
| 33 | + | |
| 34 | + (?<numoffset>[+-] |
| 35 | + (([01]\d)|2[0-3]) |
| 36 | + : |
| 37 | + ([0-5]\d) |
| 38 | + ) |
| 39 | + ) |
| 40 | + ) |
| 41 | + $ |
| 42 | + """# |
| 43 | + return try! NSRegularExpression(pattern: time, options: [.caseInsensitive]) |
| 44 | +}() |
| 45 | + |
| 46 | + |
| 47 | +func isValidTime(_ value: String) -> Bool { |
| 48 | + guard let match = timeExpression.firstMatch(in: value, range: NSMakeRange(0, value.utf16.count)) else { |
| 49 | + return false |
| 50 | + } |
| 51 | + |
| 52 | + // FIXME if seconds is 60 |
| 53 | + // Z offset: only pass if hour=23 && minute=59 |
| 54 | + // if -00:00 offset, pass |
| 55 | + // deduct or add offset to hour/minute and verify hour=23 && minute=59 |
| 56 | + |
| 57 | + return true |
| 58 | +} |
| 59 | + |
| 60 | + |
| 61 | +func validateTime(_ context: Context, _ value: String) -> AnySequence<ValidationError> { |
| 62 | + if isValidTime(value) { |
| 63 | + return AnySequence(EmptyCollection()) |
| 64 | + } |
| 65 | + |
| 66 | + return AnySequence([ |
| 67 | + ValidationError( |
| 68 | + "'\(value)' is not a valid RFC 3339 formatted time.", |
| 69 | + instanceLocation: context.instanceLocation, |
| 70 | + keywordLocation: context.keywordLocation |
| 71 | + ) |
| 72 | + ]) |
| 73 | +} |
0 commit comments