Swift String Validator. Simple lib for ios to validate string and UITextFields text for some criterias

Overview

Swift String validator

About

Library for easy and fastest string validation based on сciterias.

Instalation

KKStringValidator is available through CocoaPods. To install it, simply add the following line to your Podfile:

pod 'KKStringValidator'

Main idea

For project to project you must validate some input fields, strings, etc for thay accept some criterias (like length, exist uppercase char, exist number, etc).

KKStringValidator helps to check string for needed criterias to be accepted.

Core features

  • validate string by one or array of criterias
  • aviable force fall(break validate) when criteria fail
  • default criterias exist
  • easy add custom criteria

Example

// import lib
import KKStringValidator

// code

    // Create criterias
    let lennghtCriteria = LengthCriteria(10)
    let regexpCriteria = RegexpCriteria("[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}")

    let criterias : [Criteriable] = [lennghtCriteria, UppercaseLetterExistCriteria(), LowercaseLetterExistCriteria(), NumberExistCriteria(), regexpCriteria]


    // validate
    StringValidator(criterias).isValide("q1Q", forceExit: false, result: { validator in
        switch validator {
            case .valid:
                print("All valid")
            case .notValid(let criteria):
                print(criteria.debugErrorString)
            case .notValides(let criterias):
                print("Criterias that fails:")
                _ = criterias.map({ print($0.debugErrorString)
                })
            }
    })

Output:

Criterias that fails:
DEBUG:LengthCriteria:Lenght less than 10
DEBUG:RegexpCriteria:no mutch to regexp [A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}

UITextFieldExtension

Also created extension for UITextField.

/// extension for UITextField for validation
extension UITextField {
/// function for validating textField text
///
/// - Parameters:
///   - criterias: array of criterias
///   - forceExit: flag for force extit. default in false
///   - result: ValidatorResult object
public func validate(_ criterias : [Criteriable], forceExit:Bool = false, result:@escaping (ValidatorResult)->Void) {
    //code
}
}

Example of usage:

func textFieldDidEndEditing(_ textField: UITextField) {
    textField.validate([LengthCriteria(4)], result: { result in
        switch result {
            case .valid:
                print("All valid")
            case .notValid(let criteria):
                print(criteria.debugErrorString)
            case .notValides(let criterias):
                print("Criterias that fails:")
                _ = criterias.map({ print($0.debugErrorString)
                })
        }
    })
}

How its works

First, you must take needed criteria from the aviable criterias or create custom criteria. All criterias must conform protocol:

protocol Criteriable {
    /// debug string for helps detect problem
    var debugErrorString : String {get}

    /// Check if value conform to criteria
    ///
    /// - Parameter value: value to be checked
    /// - Returns: return true if conform
    func isConform(to value:String) -> Bool
}

Then you can validate string by choosed criterias by calling:

StringValidator([\* array of choosed criterias *\]).isValide("" \* string to must be validate *\, forceExit: false, result: { validator in
        switch validator {
            /// all criterias was passed
            case .valid:
            print("All valid")

            /// first failed criteria
            case .notValid(let criteria):

            /// all failed criterias
            case .notValides(let criterias):
        }
})

Thats all. Your string was validated and you get result.

List of aviable Criterias

struct LengthCriteria : Criteriable { \\code } \\ check string length

struct UppercaseLetterExistCriteria : Criteriable { \\code } \\ check string contains one or more char in Uppercase

struct LowercaseLetterExistCriteria : Criteriable { \\code } \\ check string contains one or more char in Lowercase

struct NumberExistCriteria : Criteriable { \\code } \\ check string exist one or more numer

struct RegexpCriteria : Criteriable { \\code } \\ check string must to RegExp

struct RangeCriteria : Criteriable { \\code } \\ check string length inside range

struct FirstCharIsLetterCriteria : Criteriable { \\code } \\ check first char is letter and optional check if in uppercase

How add custom Criteria

It's easy. Just create struct and conform protocol Criteriable. Example:

struct MyCustomCriteria : Criteriable {
    var debugErrorString: String = debugMessage(MyCustomCriteria.self, message:"some debug message")
    func isConform(to value: String) -> Bool {
        /* some logic for check */
        return false
    }
}

Thats all. Simple easy :)

Author

k.krizhanovskii, [email protected]

License

KKStatusBarService is available under the MIT license.

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

You might also like...
BonMot is a Swift attributed string library
BonMot is a Swift attributed string library

BonMot (pronounced Bon Mo, French for good word) is a Swift attributed string library. It abstracts away the complexities of the iOS, macOS, tvOS, and

Croc is a swift emoji string parsing library
Croc is a swift emoji string parsing library

Croc is a library for parsing emojis on iOS. It provides a simple and lightweight interface for detecting, generating, categorizing and managing emoji characters, making emoji-powered features an easy task for developers.

Great Swift String Pluralize Extension

Pluralize.swift Great Swift String Pluralize Extension case-insensitive tons of rules for irregular nouns (plural form) supports uncountable nouns all

👩‍🎨 Elegant Attributed String composition in Swift sauce
👩‍🎨 Elegant Attributed String composition in Swift sauce

Elegant Attributed String composition in Swift sauce SwiftRichString is a lightweight library which allows to create and manipulate attributed strings

A comprehensive, lightweight string extension for Swift

SwiftString SwiftString is a lightweight string extension for Swift. This library was motivated by having to search StackOverflow for common string op

Swift emoji string parsing library
Swift emoji string parsing library

Croc is a library for parsing emojis on iOS. It provides a simple and lightweight interface for detecting, generating, categorizing and managing emoji

Easy string decoration with styles
Easy string decoration with styles

StyleDecorator Design string simply by linking attributes. Example Create Decorator with specific Style and link it at the end of needed string or wra

Easy Attributed String Creator
Easy Attributed String Creator

The main idea of this project is to have an online tool to be able to visually add formatting to a text and get back a swift and/or objective-c code t

Owner
Kostya
Kostya
🌍⏩📄 Convert ISO8859 1-16 Encoded Text to String in Swift. Supports iOS, tvOS, watchOS and macOS.

ISO8859 Convert ISO8859 1-16 Encoded Text to String in Swift. Usage let encoding = ISO8859.part1 let string = String([...], iso8859Encoding: encoding)

Devran Cosmo Uenal 18 Jan 2, 2023
More powerful label, attributed string builder and text parser.

DDText More powerful label, attributed string builder and text parser. DDLabel More powerful label than UILabel, using TextKit. It supports features b

Daniel 16 Nov 8, 2022
Powerful text framework for iOS to display and edit rich text.

YYText Powerful text framework for iOS to display and edit rich text. (It's a component of YYKit) Features UILabel and UITextView API compatible High

null 8.8k Jan 4, 2023
Twitter Text Libraries. This code is used at Twitter to tokenize and parse text to meet the expectations for what can be used on the platform.

twitter-text This repository is a collection of libraries and conformance tests to standardize parsing of Tweet text. It synchronizes development, tes

Twitter 2.9k Dec 27, 2022
An iOS app to turn typed text into images of handwritten text in your own handwriting style.

Text-to-Handwritting © 2021 by Daniel Christopher Long An iOS app to turn typed text into images of handwritten text in your own handwriting style. ht

Daniel Long 11 Dec 29, 2022
Markdown in SwiftUI, and some other interesting components.

RoomTime RoomTime is a bundle of tools developed in my app RoomTime Lite. ( ?? RoomTime Lite is still in development) Features TextArea AutoWrap Markd

Chen SiWei 56 Dec 20, 2022
LDOMarkdownParser - Parse (some) markdown attributes into an NSAttributedString

LDOMarkdownParser Description Convert markdown text styling into an NSAttributed

Lurado 1 Feb 4, 2022
String (and more) validation for iOS

Swift Validators ?? String validation for iOS. Contents Installation Walkthrough Usage Available validators License ReactiveSwift + SwiftValidators Wa

George Kaimakas 241 Nov 13, 2022
A Cross-Platform String and Regular Expression Library written in Swift.

Guitar ?? A Cross-Platform String and Regular Expression Library written in Swift. About This library seeks to add common string manipulation function

Arthur Ariel Sabintsev 659 Dec 27, 2022
RichEditorView is a simple, modular, drop-in UIView subclass for Rich Text Editing.

RichEditorView RichEditorView is a simple, modular, drop-in UIView subclass for Rich Text Editing. Written in Swift 4 Supports iOS 8+ through Cocoapod

Caesar Wirth 1.8k Dec 24, 2022