Skip to content

Instantly share code, notes, and snippets.

@soxjke
Created October 2, 2017 23:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save soxjke/18354d1fb4ca299a8e94dbb7e6ae0274 to your computer and use it in GitHub Desktop.
Save soxjke/18354d1fb4ca299a8e94dbb7e6ae0274 to your computer and use it in GitHub Desktop.
//: Playground - noun: a place where people can play
import Foundation
precedencegroup boolImply {
associativity: left
}
infix operator ~>: boolImply
extension String {
enum ValidationMode: Int {
case email
case IPv4
}
private enum ValidatorRegexps : String {
case IPv4 = "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)"
case email = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
}
private static let modeMap : [ValidationMode: ValidatorRegexps] = [.email : .email, .IPv4 : .IPv4]
var isValidIPV4Address: Bool {
return self.isValid(as: .IPv4)
}
var isValidEmail: Bool {
return self.isValid(as: .email)
}
func isValid(as mode: ValidationMode) -> Bool {
assert(String.modeMap[mode] != nil, "Unimplemented validation mode")
return self.matches(String.modeMap[mode]?.rawValue ?? "")
}
private func matches(_ regexString: String) -> Bool {
guard let regex = try? NSRegularExpression(pattern: regexString) else { return false }
let range = NSRange(location: 0, length: self.characters.count)
return regex.rangeOfFirstMatch(in: self, range: range) == range
}
}
extension Bool {
static public func ~> (lhs: Bool, rhs: () -> ()) {
if (lhs) { rhs() }
}
}
let str = "12.2.3.50"
str.isValidIPV4Address
let str1 = "12.2.3.50a"
str1.isValidIPV4Address
let str2 = "1222.2.1.4"
let array: [String] = ["12.2.3.50", "12.2.3.50a", "1222.2.1.4"];
let filtered = array.filter { $0.isValidIPV4Address }
print(filtered)
array.forEach { (str) in
str.isValidIPV4Address ~> { print("valid") }
}
let str3 = "ababagalamaga@ukr.net"
str3.isValidIPV4Address ~> { print("\(str3) is valid IPV4")}
str3.isValidEmail ~> { print("\(str3) is valid email")}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment