String (and more) validation for iOS

Overview

Swift Validators 🔶

String validation for iOS.

Contents

ReactiveSwift + SwiftValidators

Want to use SwiftValidators with ReactiveSwift? SwiftValidatorsReactiveExtensions provides a set of extensions that play well with ValidatingProperty.

Installation

SwiftValidators is available on CocoaPods for iOS 9.0+, Xcode 8 and Swift 3.0

use_frameworks!

target 'MyProject' do
...
pod 'SwiftValidators'
...
end

It is also available through SPM:

import PackageDescription

let package = Package(
name: "MyProject",
targets: [],
dependencies: [
.Package(url: "https://github.com/gkaimakas/SwiftValidators.git",
majorVersion: 6)
]
)

Walkthrough

Usage

Validation is done using the apply function of a Validator. You can create a Validator manually or you can use on of the already available via static functions in the Validator class.

A Validator's apply function accepts an input as a nullable value that conforms to the StringConvertible protocol. By default String, NSString, Int, Float, Double and Bool conform to StringConvertible.

You can specify the Validator's behaviour when it's input is nil if you are using the static Validator function by setting the nilResponse parameter to either true or false. By default nilResponse is set to false.

Validator.exactLength(3).apply("abc") //returns true

Validator.exactLength(3).apply(true) //returns false (the string representation of true is 'true')

Validator.exactLength(3).apply(nil) //returns false since `nilResponse` is set to false by default

Valuidator.exactLength(3, nilResponse: true).apply(nil) //returns true since we set nilResponse to true

For more examples on how to call each validator you can look at the unit tests.

Logical Operators

You can combine operators using the logical AND, logical OR and Logical NOT operators ( &&, || and ! respectively).

let combinedANDValidator = Validator.required() && Validator.isTrue()

The combinedANDValidator will be true only when the value is not empty and "true"

let combinedORValidator = Validator.isTrue() || Validators.isFalse()

The combinedORValidator will be true if the value is "true" or "false", otherwise it will be false.

let reversedValidator = !Validator.isTrue()

The reversedValidator will be false when the value equals "true" and true for all other values.

Available Validators

Name Description Type Arguments Example
contains checks if it is contained in the seed func String, Bool(nilReponse=false) Validator.contains("some seed").apply("ee")
equals checks if it equals another func String, Bool(nilReponse=false) Validator.equals("aa").apply("aa")
exactLength checks if it has the exact length func Int, Bool(nilReponse=false) Validator.exactLength(2).apply("aa")
isASCII checks if it is valid ascii string func Bool(nilReponse=false) Validator.isASCII().apply("SDGSFG")
isAfter checks if it is after the date func String, String, Bool(nilReponse=false) Validator.isAfter("23/07/2015", format: "dd/MM/yyyy").apply("24/07/2015")
isAlpha checks if it has only letters func Bool(nilReponse=false) Validator.isAlpha().apply("abc")
isAlphanumeric checks if it has letters and numbers only func Bool(nilReponse=false) Validator.isAlphanumeric().apply("abc123")
isBase64 checks if it a valid base64 string func Bool(nilReponse=false) Validator.isBase64().apply("some string")
isBefore checks if it is before the date func String, String, Bool(nilReponse=false) Validator.isBefore("25/09/1987", format: "dd/MM/yyyy").apply("29/03/1994")
isBool checks if it is boolean func Bool(nilReponse=false) Validator.isBool().apply("true")
isCreditCard checks if it is a credit card number func Bool(nilReponse=false) Validator.isCreditCard().apply("123")
isDate checks if it is a valid date func String, Bool(nilReponse=false) Validator.isDate("dd/MM/yyyy").apply("25/09/1987")
isEmail checks if it is an email func Bool(nilReponse=false) Validator.isEmail().apply("[email protected]")
isEmpty checks if it is an empty string func Bool(nilReponse=false) Validator.isEmpty().apply("")
isFQDN checks if it is fully qualified domain name func FQDNOptions or empty, Bool(nilReponse=false) Validator.isFQDN().apply("ABC")
isFalse checks if it is false func Bool(nilReponse=false) Validator.isFalse().apply("false")
isFloat checks if it is a float number func Bool(nilReponse=false) Validator.isFloat().apply("2.3e24")
isHexColor checks if it is a valid hex color func Bool(nilReponse=false) Validator.isHexColor().apply("#fafafa")
isHexadecimal checks if it is a hexadecimal value func Bool(nilReponse=false) Validator.isHexadecimal().apply("abcdef")
isIP checks if it is a valid IP (4 |6) func Bool(nilReponse=false) Validator.isIP().apply("0.0.0.0")
isIPv4 checks if it is a valid IPv4 func Bool(nilReponse=false) Validator.isIPv4().apply("0.0.0.0")
isIPv6 checks if it is a valid IPv6 func Bool(nilReponse=false) Validator.isIPv6().apply("::")
isISBN checks if it is a valid ISBN func ISBN, Bool(nilReponse=false) Validator.isISBN(.v13).apply("asdf")
isIn checks if the value exists in the supplied array func Array, Bool(nilReponse=false) Validator.isIn(["a","b","c"]).apply("a")
isInt checks if it is a valid integer func Bool(nilReponse=false) Validator.isInt().apply("123")
isLowercase checks if it only has lowercase characters func Bool(nilReponse=false) Validator.isLowercase().apply("asdf")
isMongoId checks if it a hexadecimal mongo id func Bool(nilReponse=false) Validator.isMongoId()("adfsdffsg")
isNumeric checks if it is numeric func Bool(nilReponse=false) Validator.isNumeric().apply("+123")
isPhone checks if it is a valid phone func Phone, Bool(nilReponse=false) Validator.isPhone(.el_GR).apply("6944848966")
isPostalCode checks it is a valid postal code func PostalCode, Bool(nilResponse=false) Validator.isPostalCode(.GR).apply("30 006")
isTrue checks if it is true func Bool(nilReponse=false) Validator.isTrue().apply("true")
isURL checks if it is a valid URL func Bool(nilReponse=false) Validator.isURL().apply("http://www.google.com")
isUUID checks if it is a valid UUID func Bool(nilReponse=false) Validator.isUUID().apply("243-124245-2235-123")
isUppercase checks if has only uppercase letter func Bool(nilReponse=false) Validator.isUppercase().apply("ABC")
maxLength checks if the length does not exceed the max length func Int, Bool(nilReponse=false) Validator.maxLength(2).apply("ab")
minLength checks if the length isn't lower than func Int, Bool(nilReponse=false) Validator.minLength(1).apply("213")
required checks if it is not an empty string func Bool(nilReponse=false) Validator.required().apply("")
regex checks that the value matches the regex from start to finish func String, Bool(nilReponse=false) Validator.regex(pattern).apply("abcd")

*FQDNOptions is a class that is used on isFQDN for configuration purposes. It can be instantiated like this:

FQDNOptions(requireTLD: Bool, allowUnderscores: Bool, allowTrailingDot: Bool)

License MIT

Copyright (c) George Kaimakas [email protected]

Permission is hereby granted, free of charge, to any person obtaining 
acopy 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.
Comments
  • Validation error ordering issue

    Validation error ordering issue

    I want to show validation error messages at time of user tap on Registration button. Now the issue is

    func validationFailed(_ errors:[(Validatable ,ValidationError)])

    here errors parameter returns the fields in unordered set.

    can we show error messages in ordered set?

    opened by ronak-selldo 5
  • Latest Update Errors

    Latest Update Errors

    Since updating to latest version.. I get the error "Type 'Validator' (aka 'Optional -> Bool') has no member 'isEmail'"

    MY CODE

    import UIKit
    import SwiftValidators
    
    class TestVC: UIViewController
    {
        override func viewDidLoad()
        {
            super.viewDidLoad();
    
            let is_email = Validator.isEmail("[email protected]");
    
            print("is_email: \(is_email)");
        }
    }
    
    
    opened by oliverbytes 4
  • PostalCode.IT.rawValue returns wrong value

    PostalCode.IT.rawValue returns wrong value

    case DE, EE, ES, FI, IT, KE, LT, MX, SA, UA = "\\d{5}"
    
    (lldb) po PostalCode.IT.rawValue
    "IT"
    (lldb) po PostalCode.UA.rawValue
    "\\d{5}"
    
    opened by Neirys 3
  • Added validation for Dutch, Belgian and Belgian mobile phones

    Added validation for Dutch, Belgian and Belgian mobile phones

    I tried to add validation for both Dutch and Belgian phone numbers and Belgian mobile phone numbers.

    I explicitly separated Belgian phone numbers and Belgian mobile phone numbers, as they differ and I want to distinguish them to be able to provide the user better feedback in what is wrong.

    opened by cloudcosmonaut 2
  • Carthage support for 8.0.0 version

    Carthage support for 8.0.0 version

    Added Carthage support to the latest version. No change has been made to the code. Had to add Pods folder to source control because of a build error in Carthage. Note: Please delete the 8.0.0 tag and create it again.

    opened by vdeep 1
  • Email validator fails to validate valid email

    Email validator fails to validate valid email

    opened by mruvim 1
  • Failed with FQDN verification of domain name including numbers other than 9

    Failed with FQDN verification of domain name including numbers other than 9

    The title is as follows.

    Success: www9.example.com Failed : www1.exaple.com

    I think there is a problem with the following code.

    Validators.swift(L320) if (!self.regex("[a-z\u{00a1}-\u{ffff0}-9-]+")(_part)){

    Thank you.

    opened by kumeichi 1
  • Example Swift Syntax

    Example Swift Syntax

    Hi, I am sure this should be pretty easy. I am fairly new to swift. Cant figure out code syntax to make this work.

    Could you share some simple examples validating a variable in Swift 3 as well as validating data in a text field in swift 3.

    Thank you.

    opened by jrlanders 1
  • Carthage Issue

    Carthage Issue

    *** Checking out SwiftValidators at "5.1.1"
    *** xcodebuild output can be found in /var/folders/qp/sfd3f5691qx3hhvljx3r24f80000gn/T/carthage-xcodebuild.dbvqbI.log
    *** Skipped building SwiftValidators due to the error:
    Dependency "SwiftValidators" has no shared framework schemes
    
    opened by ntanyeri 1
  • Carthage support

    Carthage support

    Here is another approach to providing Carthage support. In my previous pull request, I had committed the Pods directory so that the files included in the main project are within the source. But as per your suggestion that Pods directory should not be committed, I had to make some changes.

    -> Removed Quick and Nimble dependencies using Cocoapods -> Added the dependencies using Carthage. This way, no extra file is included in the main project. For testing, the users will have to do a carthage bootstrap. -> Shared the framework schema -> No other change has been made to the code.

    Let me know if this is okay.

    opened by vdeep 0
  • Advantages from using this library

    Advantages from using this library

    Hi there, looks interesting 🎉 I read the readme and I'm still having a question.

    What's a real world scenario where this library could help. And what are the advantages of using this library?

    Will this make my code more readable? So it's like a syntactic sugar?

    I think this question could be answered in the readme. What do you think?

    opened by Nikoloutsos 3
Releases(2.2.0)
Owner
George Kaimakas
iOS Engineer
George Kaimakas
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
🌍⏩📄 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
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
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

Rightpoint 3.4k Dec 30, 2022
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.

Joe Kalash 127 Nov 20, 2022
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

Joshua Arvin Lat 193 Nov 8, 2022
👩‍🎨 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

Daniele Margutti 2.9k Jan 5, 2023
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

Andrew Mayne 1.6k Dec 30, 2022
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

Dmytro Pylypenko 15 Nov 4, 2021
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

Joe Kalash 125 Sep 27, 2021
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

Andres Canal 283 Dec 27, 2022
A simple library for building attributed strings, for a more civilized age.

Veneer A simple library for building attributed strings, for a more civilized age. Veneer was created to make creating attributed strings easier to re

Wess Cope 26 Dec 27, 2022
Markdown parsing and rendering for iOS and OS X

CocoaMarkdown Markdown parsing and rendering for iOS and macOS CocoaMarkdown is a cross-platform framework for parsing and rendering Markdown, built o

Indragie Karunaratne 1.2k Dec 12, 2022
An NSPredicate DSL for iOS, OSX, tvOS, & watchOS. Inspired by SnapKit and lovingly written in Swift.

PrediKit A Swift NSPredicate DSL for iOS & OS X inspired by SnapKit, lovingly written in Swift, and created by that weird dude at KrakenDev. If you're

Hector Matos 542 Sep 24, 2022
A library for formatting strings on iOS and macOS

Sprinter Introduction What? Why? How? Usage Installation Integration Localization Thread Safety Advanced Usage Introduction What? Sprinter is a librar

Nick Lockwood 168 Feb 6, 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
CodeMirror-Swift is a lightweight wrapper of CodeMirror for macOS and iOS

CodeMirror-Swift is a lightweight wrapper of CodeMirror for macOS and iOS. Features ?? Lightweight CodeMirror wrapper (build 5.52.2) ✅ 100% Native Swi

Proxyman 86 Dec 30, 2022
Easiest way to create an attributed UITextView (with support for multiple links and from html)

AttributedTextView Easiest way to create an attributed UITextView (with support for multiple links and html). See the demo app and the playground for

Edwin Vermeer 430 Nov 24, 2022