Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import Foundation
- /// Provides an interface to validate that the given input matches a set of rules.
- struct TextFieldValidation {
- /// Defines a set of rules that the input can be validated for.
- enum Rule: Hashable {
- /// Rule that the input is not empty.
- case notEmpty
- /// Rule that the input is part of the defined character set.
- case isIn(CharacterSet)
- /// Rule that the input can be converted into a double type.
- case isDouble
- /// Rule that the number of digits doesn't exceed the limit.
- case limit(Int)
- /// Combines `isIn(.decimalDeigits)`, and `isDouble` rules.
- case isDecimal
- /// Rule like `limit()` but with a hard limit of 60, `notEmpty`, and `isIn(.alphanumerics.union(.symbols))`.
- /// Used to validate text inputs.
- case limitText
- /// Rule like `limit()` but with a hard limit of 6, `notEmpty`, `isIn(.decimalDigits)`, and `isDouble` rules.
- /// Used to validate numeric field inputs.
- case limitNumbers
- }
- // MARK: - Business
- /// Returns true or false if the given input passes all of the rules.
- func validate(_ input: String, against rules: Set<Rule>) -> Bool {
- for rule in rules {
- if validateRule(rule, input: input) == false {
- return false
- }
- }
- return true
- }
- private func validateRule(_ rule: Rule, input: String) -> Bool {
- switch rule {
- case .notEmpty:
- return validateNotEmpty(input)
- case .isIn(let set):
- return validateIsInCharacterSet(set, input: input)
- case .isDouble:
- return validateIsDouble(input)
- case .limit(let limit):
- return validateLimit(limit, input: input)
- case .isDecimal:
- return validate(input, against: [.isIn(.decimalDigits), .isDouble])
- case .limitText:
- return validate(input, against: [.notEmpty, .limit(60), .isIn(.alphanumerics.union(.symbols))])
- case .limitNumbers:
- return validate(input, against: [.notEmpty, .isDouble, .limit(6), .isIn(.decimalDigits)])
- }
- }
- private func validateNotEmpty(_ input: String) -> Bool {
- let trimmedInput = input.trimmingCharacters(in: .whitespacesAndNewlines)
- return trimmedInput.isEmpty == false
- }
- private func validateIsInCharacterSet(_ set: CharacterSet, input: String) -> Bool {
- return input.rangeOfCharacter(from: set) != nil
- }
- private func validateIsDouble(_ input: String) -> Bool {
- return Double(input) != nil
- }
- private func validateLimit(_ limit: Int, input: String) -> Bool {
- return input.count <= limit
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement