Skip to content
This repository was archived by the owner on Nov 16, 2020. It is now read-only.

Date validation #34

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
37 changes: 37 additions & 0 deletions Sources/Validation/Validators/DateValidator.swift
Original file line number Diff line number Diff line change
@@ -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<T> {
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")
}
}
}