Repository Public MIT
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : SP GlassKit7// File : Sources/SPGlassForms/Forms/GlassFieldValidation.swift8// Module : SPGlassForms9// Repository : https://git.spboucher.ai/sp-glasskit10// Project Website : https://glass.spboucher.ai11// Created : 2026-12-0212// Last Modified : 2026-12-0213//14// Author : Simon-Pierre Boucher15// Position : Professor of Finance16// Institution : Université du Québec en Outaouais (UQO)17// Organization : SP Boucher18// Website : https://spboucher.ai19// Git : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development : dev@spboucher.ai23// Support : support@spboucher.ai24// Security/Admin : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License : MIT33//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041import Foundation42import SPGlassCore4344/// One validation rule of a text field.45public struct GlassFieldRule: Sendable {46 enum Kind: Sendable {47 case required48 case minLength(Int)49 case maxLength(Int)50 case predicate(@Sendable (String) -> Bool)51 }5253 let kind: Kind54 /// Message supplied by the caller; `nil` uses GlassKit's localised message.55 let message: String?5657 /// The value must contain something other than white space.58 public static func required(message: String? = nil) -> GlassFieldRule {59 GlassFieldRule(kind: .required, message: message)60 }6162 /// The value must hold at least `count` characters (user-perceived characters, so an emoji counts as one).63 public static func minLength(_ count: Int, message: String? = nil) -> GlassFieldRule {64 GlassFieldRule(kind: .minLength(count), message: message)65 }6667 /// The value must hold at most `count` characters.68 public static func maxLength(_ count: Int, message: String? = nil) -> GlassFieldRule {69 GlassFieldRule(kind: .maxLength(count), message: message)70 }7172 /// The value must satisfy `isValid`. The message is required because GlassKit cannot guess the rule.73 public static func custom(message: String, _ isValid: @escaping @Sendable (String) -> Bool) -> GlassFieldRule {74 GlassFieldRule(kind: .predicate(isValid), message: message)75 }7677 /// The message of this rule if `text` breaks it, otherwise `nil`.78 ///79 /// Length and custom rules accept an empty value: emptiness is the business of ``required(message:)``.80 func failure(for text: String) -> String? {81 switch kind {82 case .required:83 return text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ? message ?? GlassL10n.string(.fieldRequired) : nil84 case .minLength(let count):85 return !text.isEmpty && text.count < count ? message ?? GlassL10n.string(.fieldTooShort, count) : nil86 case .maxLength(let count):87 return text.count > count ? message ?? GlassL10n.string(.fieldTooLong, count) : nil88 case .predicate(let isValid):89 return !text.isEmpty && !isValid(text) ? message ?? GlassL10n.string(.error) : nil90 }91 }92}9394/// When a field starts showing its validation message.95public enum GlassValidationTrigger: String, CaseIterable, Sendable {96 /// As soon as the value is invalid, including before the user typed anything.97 case always98 /// Once the user has left the field or submitted it, so that nobody is told off while still typing.99 case afterEditing100 /// Never by itself: the host shows errors through `errorMessage`.101 case never102}103104/// The rules of a field, checked in order. Pure: the same text always gives the same result.105///106/// ```swift107/// let validation = GlassFieldValidation(.required(), .minLength(3), .custom(message: "No spaces") { !$0.contains(" ") })108/// validation.message(for: "ab") // "Enter at least 3 characters"109/// ```110public struct GlassFieldValidation: Sendable {111 public let rules: [GlassFieldRule]112113 public init(_ rules: GlassFieldRule...) {114 self.rules = rules115 }116117 public init(rules: [GlassFieldRule]) {118 self.rules = rules119 }120121 /// A validation without rules: every value is valid.122 public static let none = GlassFieldValidation(rules: [])123124 /// Whether one of the rules requires a value. Fields use it to announce "Required".125 public var isRequired: Bool {126 rules.contains { if case .required = $0.kind { true } else { false } }127 }128129 /// The message of the first broken rule, or `nil` when the text is valid.130 public func message(for text: String) -> String? {131 for rule in rules {132 if let failure = rule.failure(for: text) { return failure }133 }134 return nil135 }136137 public func isValid(_ text: String) -> Bool {138 message(for: text) == nil139 }140141 /// The message a field displays.142 ///143 /// - Parameters:144 /// - externalError: an error decided by the host (a server answer, for example). It always wins.145 /// - hasFinishedEditing: whether the user left the field or submitted it at least once.146 public func visibleMessage(for text: String, trigger: GlassValidationTrigger, hasFinishedEditing: Bool, externalError: String? = nil) -> String? {147 if let externalError, !externalError.isEmpty { return externalError }148 switch trigger {149 case .always: return message(for: text)150 case .afterEditing: return hasFinishedEditing ? message(for: text) : nil151 case .never: return nil152 }153 }154}155156/// Automatic capitalisation of a text field. Applied on iOS and iPadOS; macOS has no such setting.157public enum GlassTextCapitalization: String, CaseIterable, Sendable {158 case never, words, sentences, characters159}160161/// The software keyboard of a text field. Applied on iOS and iPadOS.162public enum GlassKeyboardKind: String, CaseIterable, Sendable {163 case standard, asciiCapable, emailAddress, url, numberPad, decimalPad, phonePad164}165166/// What a field holds, so that the system can offer AutoFill.167public enum GlassTextContentKind: String, CaseIterable, Sendable {168 case name, givenName, familyName, emailAddress, username, password, newPassword, oneTimeCode169 case telephoneNumber, url, postalCode, fullStreetAddress, organizationName170}171172/// Text input settings of a field.173public struct GlassTextInputConfiguration: Equatable, Sendable {174 public var autocorrectionDisabled: Bool175 public var capitalization: GlassTextCapitalization176 public var keyboard: GlassKeyboardKind177 public var contentKind: GlassTextContentKind?178179 public init(180 autocorrectionDisabled: Bool = false,181 capitalization: GlassTextCapitalization = .sentences,182 keyboard: GlassKeyboardKind = .standard,183 contentKind: GlassTextContentKind? = nil184 ) {185 self.autocorrectionDisabled = autocorrectionDisabled186 self.capitalization = capitalization187 self.keyboard = keyboard188 self.contentKind = contentKind189 }190191 /// Sentences capitalised, autocorrection on, standard keyboard.192 public static let standard = GlassTextInputConfiguration()193 /// An e-mail address: no autocorrection, no capitalisation, e-mail keyboard and AutoFill.194 public static let email = GlassTextInputConfiguration(autocorrectionDisabled: true, capitalization: .never, keyboard: .emailAddress, contentKind: .emailAddress)195 /// A user name: no autocorrection, no capitalisation, AutoFill.196 public static let username = GlassTextInputConfiguration(autocorrectionDisabled: true, capitalization: .never, keyboard: .asciiCapable, contentKind: .username)197 /// A web address.198 public static let url = GlassTextInputConfiguration(autocorrectionDisabled: true, capitalization: .never, keyboard: .url, contentKind: .url)199 /// A whole number typed on the number pad.200 public static let number = GlassTextInputConfiguration(autocorrectionDisabled: true, capitalization: .never, keyboard: .numberPad)201 /// A person's name: words capitalised, no autocorrection.202 public static let name = GlassTextInputConfiguration(autocorrectionDisabled: true, capitalization: .words, contentKind: .name)203}204