diff --git a/Sources/Validation/Validators/DateValidator.swift b/Sources/Validation/Validators/DateValidator.swift new file mode 100644 index 0000000..c8209f3 --- /dev/null +++ b/Sources/Validation/Validators/DateValidator.swift @@ -0,0 +1,37 @@ +extension Validator where T == String { + /// Validates whether a `String` is a valid date. + /// + /// try validations.add(\.createdAt, .date(formatter: dateFormatter)) + /// + public static func date(_ dateFormatter: DateFormatter) -> Validator { + return DateValidator(dateFormatter: dateFormatter).validator() + } +} + +// MARK: Private + +/// Validates whether a string is a valid date. +fileprivate struct DateValidator: ValidatorType { + /// See `ValidatorType`. + public var validatorReadable: String { + return "a valid date" + } + + /// the DateFormatter used to validate the string + let dateFormatter: DateFormatter + + /// Creates a new `DateValidator`. + public init(dateFormatter: DateFormatter) { + self.dateFormatter = dateFormatter + } + + /// See `Validator`. + public func validate(_ s: String) throws { + guard + s.isEmpty || + dateFormatter.date(from: s) != nil + else { + throw BasicValidationError("is not a valid date") + } + } +}