Skip to content

Instantly share code, notes, and snippets.

@valexa
Last active January 30, 2017 11:45
Show Gist options
  • Save valexa/8c478844b5d67f7d8ae15879343154e3 to your computer and use it in GitHub Desktop.
Save valexa/8c478844b5d67f7d8ae15879343154e3 to your computer and use it in GitHub Desktop.
public func RegexValidationWithMessage(_ message:String, regex:String, allowingNull:Bool = true) -> Validation<String>? {
if let regex = try? NSRegularExpression(pattern: regex, options: .CaseInsensitive) {
return Validation<String>(message: message, validation: { (value) -> Bool in
let nullValidation = NonEmptyStringValidation("")
guard let stringValue = value else {
return false
}
if !allowingNull && nullValidation.validate(value: stringValue) != .Valid {
return false
}
if allowingNull && stringValue.isEmpty {
return true
}
return regex.matchesInString(stringValue, options: NSMatchingOptions.ReportProgress, range: NSMakeRange(0, stringValue.characters.count)).count > 0
})
} else {
return nil
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment