Skip to content

Custom Validators

Jeff Hurray edited this page Apr 13, 2017 · 2 revisions

Custom Validators

TextSelectionValidator

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
}

Required

  • 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

Optional

  • 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 to nil.
  • 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.

Example

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())
    }
}

Other Protocols

ContainerTextSelectionValidator

ContainerTextSelectionValidator acts as a wrapper over an instance conforming to TextSelectionValidator. There is a ContainerValidator struct provided that implements this protocol.

Required
  • validator: TextSelectionValidator is the validator that is wrapped.

CompositeTextSelectionValidator

CompositeTextSelectionValidator acts as a wrapper over multiple instances conforming to TextSelectionValidator. There is a CompositeValidator struct provided that implements this protocol.

Required
  • validators: [TextSelectionValidator] is the array of validators that is wrapped.