summaryrefslogtreecommitdiff
path: root/Example Apps/Example Swift/TextValidator.swift
blob: 3c0e5645e9a26680660ea25b36d4b584b4ba56fe (plain)
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
//
//  TextValidator.swift
//  SmartDeviceLink
//
//  Created by Nicole on 7/20/18.
//  Copyright © 2018 smartdevicelink. All rights reserved.
//

import Foundation

class TextValidator {
    private static let validCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789. "

    class func validateText(_ text: String, length: Int) -> String {
        if text.isEmpty { return text }
        let filteredText = filterUnsupportedCharacters(text)
        let condensedString = filteredText.condenseWhitespace
        let truncatedString = condensedString.truncate(length: length)
        return truncatedString
    }

    private class func filterUnsupportedCharacters(_ text:String) -> String {
        return String(text.filter { validCharacters.contains($0) } )
    }
}

extension String {
    func truncate(length: Int, trailing: String = "…") -> String {
        return (self.count > length) ? self.prefix(length) + trailing : self
    }

    var condenseWhitespace: String {
        let components = self.components(separatedBy: .whitespacesAndNewlines)
        return components.filter { !$0.isEmpty }.joined(separator: " ")
    }
}