-
Notifications
You must be signed in to change notification settings - Fork 28
Custom Validators
Jeff Hurray edited this page Apr 13, 2017
·
2 revisions
Below is the TextSelectionValidator
protocol that a custom validator must conform to:
public protocol TextSelectionValidator: TextSelectionAppearance {
var identifier: String {get}
var selectionAttributes: [String: Any]? {get}
var replacementText: String? {get}
func validate(text: String) -> Bool
}
-
func validate(text: String) -> Bool
: A method that determines whether or not text is valid. -
identifier: String
is a unique identifier similar to a reuse identifier for collection view cells
-
selectionAttributes: [String: Any]?
are attributes that will be used to create an attributed string. This is optionally overridable if you want custom styling for the selectable text. Defaults tonil
. -
replacementText: String?
is an optionally overridable property that supplies text that will replace the valid text in a string. This allows you to create hyperlinkable text even if you are validating a URL.
Below is an example of how to create a validator that matches specific prefixes.
public struct PrefixValidator: TextSelectionValidator {
private(set) var text: String
private(set) var caseSensitive: Bool
public init(prefix: String, caseSensitive: Bool = false) {
self.text = prefix
self.caseSensitive = caseSensitive
}
public var identifier: String {
return "\(typeString).begins_with.\(text)"
}
public func validate(text: String) -> Bool {
if caseSensitive {
return text.hasPrefix(self.text)
}
return text.lowercased().hasPrefix(self.text.lowercased())
}
}
ContainerTextSelectionValidator
acts as a wrapper over an instance conforming to TextSelectionValidator
. There is a ContainerValidator
struct
provided that implements this protocol.
-
validator: TextSelectionValidator
is the validator that is wrapped.
CompositeTextSelectionValidator
acts as a wrapper over multiple instances conforming to TextSelectionValidator
. There is a CompositeValidator
struct
provided that implements this protocol.
-
validators: [TextSelectionValidator]
is the array of validators that is wrapped.