Skip to content

Instantly share code, notes, and snippets.

@rjstelling
Created March 23, 2020 10:09
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rjstelling/649ff0e848af4e03f461386f4548b72d to your computer and use it in GitHub Desktop.
Save rjstelling/649ff0e848af4e03f461386f4548b72d to your computer and use it in GitHub Desktop.
A `@propertyWrapper` that validates a string using a regular expression. If the string matches then it is assigned to the property if it does not then the property is net to nil. Also included is an example of validating email addresses.
import Foundation
@propertyWrapper
public struct RegularExpressionValidation {
private var _verifiedString: String?
private let _regexPattern: String
private lazy var _regex: NSRegularExpression? = try? NSRegularExpression(pattern: _regexPattern, options: [.caseInsensitive])
public init(_ regexString: String) {
_regexPattern = regexString
}
public var wrappedValue: String? {
get { _verifiedString }
set {
guard let searchString = newValue else { _verifiedString = nil; return }
let range = NSRange(searchString.startIndex..<searchString.endIndex, in: searchString)
if _regex?.firstMatch(in: searchString, options: [], range: range) != nil {
_verifiedString = searchString
}
else {
_verifiedString = nil
}
}
}
}
@propertyWrapper
public struct EmailValidation {
@RegularExpressionValidation("^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])$")
private var _stringEmail: String?
public init(wrappedValue value: String?) {
_stringEmail = value
}
public var wrappedValue: String? {
get { _stringEmail }
set { _stringEmail = newValue }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment