-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathNSTextField+Validation.swift
More file actions
52 lines (46 loc) · 1.76 KB
/
NSTextField+Validation.swift
File metadata and controls
52 lines (46 loc) · 1.76 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
43
44
45
46
47
48
49
50
51
52
//
// Validator
// Copyright © 2023 Space Code. All rights reserved.
//
#if os(macOS)
import AppKit
extension NSTextField: IUIValidatable {
/// The value of the text field to validate.
/// Returns an empty string if `text` is nil.
public var inputValue: String {
stringValue
}
/// 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 {
NotificationCenter.default.addObserver(
self,
selector: #selector(textFieldDidChange(_:)),
name: NSControl.textDidChangeNotification,
object: self
)
} else {
NotificationCenter.default.removeObserver(
self,
name: NSControl.textDidChangeNotification,
object: self
)
}
}
// MARK: Private
/// Called automatically when the text field changes (if `validateOnInputChange` is enabled).
/// Performs validation using all rules stored in `validationRules`.
///
/// - Parameter notification: The notification containing the text field.
@objc
private func textFieldDidChange(_ notification: Notification) {
guard notification.object as? NSTextField === self else { return }
validate(rules: validationRules)
}
}
#endif