75 lines
1.7 KiB
Swift
75 lines
1.7 KiB
Swift
//
|
|
// FormFieldable.swift
|
|
// VDS
|
|
//
|
|
// Created by Matt Bruce on 7/22/22.
|
|
//
|
|
|
|
import Foundation
|
|
|
|
/// Protocol used for a FormField object.
|
|
public protocol FormFieldable {
|
|
associatedtype ValueType = AnyHashable
|
|
|
|
/// Unique Id for the Form Field object within a Form.
|
|
var inputId: String? { get set }
|
|
|
|
/// Value for the Form Field.
|
|
var value: ValueType? { get set }
|
|
}
|
|
|
|
public struct AnyRule<ValueType> {
|
|
private let _isValid: (ValueType?) -> Bool
|
|
public let errorMessage: String
|
|
|
|
init<R: Rule>(_ rule: R) where R.ValueType == ValueType {
|
|
self._isValid = rule.isValid
|
|
self.errorMessage = rule.errorMessage
|
|
}
|
|
|
|
public func isValid(value: Any?) -> Bool {
|
|
guard let typedValue = value as? ValueType? else {
|
|
return false
|
|
}
|
|
return _isValid(typedValue)
|
|
}
|
|
}
|
|
|
|
public protocol Rule<ValueType> {
|
|
associatedtype ValueType
|
|
func isValid(value: ValueType?) -> Bool
|
|
var errorMessage: String { get }
|
|
}
|
|
|
|
public class FieldValidator<Field:FormFieldable>{
|
|
public var field: Field
|
|
public var rules: [AnyRule<Field.ValueType>]?
|
|
public var errorMessages = [String]()
|
|
|
|
public init(field: Field, rules: [AnyRule<Field.ValueType>]? = nil) {
|
|
self.field = field
|
|
self.rules = rules
|
|
}
|
|
|
|
public var errorMessage: String? {
|
|
errorMessages.joined(separator: "\r")
|
|
}
|
|
|
|
public func validate() -> Bool{
|
|
errorMessages.removeAll()
|
|
|
|
guard let rules else {
|
|
return true
|
|
}
|
|
|
|
for rule in rules {
|
|
if !rule.isValid(value: field.value) {
|
|
errorMessages.append(rule.errorMessage)
|
|
return false
|
|
}
|
|
}
|
|
return true
|
|
}
|
|
|
|
}
|