From 351c1b3acb2aba0331afcfce221d48a0e39a8a39 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Je=CC=81ro=CC=82me=20Danthinne?= Date: Tue, 28 May 2019 11:30:47 +0200 Subject: [PATCH] Added a date validator --- .../Validation/Validators/DateValidator.swift | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Sources/Validation/Validators/DateValidator.swift 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") + } + } +}