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
🚦 Validation library depends on SwiftUI & Combine. Reactive and fully customizable.

?? Validation library depends on SwiftUI & Combine. Reactive and fully customizable.

Alexo 14 Dec 30, 2022
Drop in user input validation for your iOS apps.

Validator Validator is a user input validation library written in Swift. It's comprehensive, designed for extension, and leaves the UI up to you. Here

Adam Waite 1.4k Dec 29, 2022
RxValidator Easy to Use, Read, Extensible, Flexible Validation Checker.

RxValidator Easy to Use, Read, Extensible, Flexible Validation Checker. It can use without Rx. Requirements RxValidator is written in Swift 4.

GeumSang Yoo 153 Nov 17, 2022
Swift Validator is a rule-based validation library for Swift.

Swift Validator is a rule-based validation library for Swift. Core Concepts UITextField + [Rule] + (and optional error UILabel) go into

null 1.4k Dec 29, 2022
Validation plugin for Moya.Result

MoyaResultValidate Why? Sometimes we need to verify that the data returned by the server is reasonable, when Moya returns Result.success. JSON returne

Insect_QY 1 Dec 15, 2021
Input Validation Done Right. A Swift DSL for Validating User Input using Allow/Deny Rules

Valid Input Validation Done Right. Have you ever struggled with a website with strange password requirements. Especially those crazy weird ones where

Mathias Quintero 37 Nov 3, 2022
A framework to validate inputs of text fields and text views in a convenient way.

FormValidatorSwift The FormValidatorSwift framework allows you to validate inputs of text fields and text views in a convenient way. It has been devel

ustwo™ 500 Nov 29, 2022
Input Mask is an Android & iOS native library allowing to format user input on the fly.

Migration Guide: v.6 This update brings breaking changes. Namely, the autocomplete flag is now a part of the CaretGravity enum, thus the Mask::apply c

red_mad_robot 548 Dec 20, 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
iOS validation framework with form validation support

ATGValidator ATGValidator is a validation framework written to address most common issues faced while verifying user input data. You can use it to val

null 51 Oct 19, 2022
iOS validation framework with form validation support

ATGValidator ATGValidator is a validation framework written to address most common issues faced while verifying user input data. You can use it to val

null 51 Oct 19, 2022
Swift String Validator. Simple lib for ios to validate string and UITextFields text for some criterias

Swift String validator About Library for easy and fastest string validation based on сciterias. Instalation KKStringValidator is available through Coc

Kostya 17 Dec 21, 2019
StyledTextKit is a declarative attributed string library for fast rendering and easy string building.

StyledTextKit is a declarative attributed string library for fast rendering and easy string building. It serves as a simple replacement to NSAttribute

GitHawk 1.2k Dec 23, 2022
KIEM - Open Source Library, converting mistyped Korean string into English string

KIEM Open Source Library, converting misspelled Korean string into English strin

Samuel Kim 1 Feb 18, 2022
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
Tools for making SwiftUI navigation simpler, more ergonomic and more precise.

SwiftUI Navigation Tools for making SwiftUI navigation simpler, more ergonomic and more precise. Motivation Tools Navigation overloads Navigation view

Point-Free 1.1k Jan 1, 2023
A modal passcode input and validation view controller for iOS

TOPasscodeViewController A modal passcode input and validation view controller for iOS. TOPasscodeViewController is an open-source UIViewController su

Tim Oliver 381 Dec 5, 2022
MMVMi: A Validation Model for MVC and MVVM Design Patterns in iOS Applications

MMVMi MMVMi: A Validation Model for MVC and MVVM Design Patterns in iOS Applications Motivation Design patterns have gained popularity as they provide

Mariam AlJamea 11 Aug 19, 2022
A modal passcode input and validation view controller for iOS

TOPasscodeViewController A modal passcode input and validation view controller for iOS. TOPasscodeViewController is an open-source UIViewController su

Tim Oliver 381 Dec 5, 2022
SwiftCop is a validation library fully written in Swift and inspired by the clarity of Ruby On Rails Active Record validations.

SwiftCop is a validation library fully written in Swift and inspired by the clarity of Ruby On Rails Active Record validations. Objective Build a stan

Andres Canal 542 Sep 17, 2022