-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathUITextField+Validation.swift
More file actions
42 lines (36 loc) · 1.4 KB
/
UITextField+Validation.swift
File metadata and controls
42 lines (36 loc) · 1.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
//
// Validator
// Copyright © 2023 Space Code. All rights reserved.
//
#if os(iOS)
import UIKit
extension UITextField: IUIValidatable {
/// The value of the text field to validate.
/// Returns an empty string if `text` is nil.
public var inputValue: String {
text ?? ""
}
/// The type of input for validation.
public typealias Input = String
/// Enables or disables automatic validation when the text changes.
///
/// - Parameter isEnabled: If true, validation is triggered on every text change.
/// If false, the target-action is removed.
public func validateOnInputChange(isEnabled: Bool) {
if isEnabled {
addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)
} else {
removeTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)
}
}
// MARK: Private
/// Called automatically when the text field changes (if `validateOnInputChange` is enabled).
/// Performs validation using all rules stored in `validationRules`.
///
/// - Parameter textField: The text field triggering the action.
@objc
private func textFieldDidChange(_: UITextField) {
validate(rules: validationRules)
}
}
#endif