Last active
January 19, 2026 12:34
-
-
Save hellensoloviy/ef4edc5c57c6aa0429583aedce0b25fb to your computer and use it in GitHub Desktop.
Simple RegexValidator for strings (+ Obj-c compatible)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import Foundation | |
| @objc class RegexValidator: NSObject { | |
| @objc enum ValidationPattern: Int { | |
| case email = 0 | |
| case notEmpty | |
| case stateInUSA | |
| case stateInAustralia | |
| case state | |
| var pattern: String { | |
| switch self { | |
| case .email: return "[A-Za-z0-9!#$%&'*+/=?^self.`{|}~-]+(?:\\.[A-Za-z0-9!#$%&'*+/=?^self.`{|}~-]+)*@(?:[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?\\.)+[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?" | |
| case .notEmpty: return "([A-Za-z ]+)" | |
| case .stateInUSA: return "[A-Z]{2}" | |
| case .stateInAustralia: return "[A-Z]{3}" | |
| case .state: return "[A-Z]{2,3}" | |
| } | |
| } | |
| } | |
| @objc class func transformToOBJCString(_ pattern: ValidationPattern) -> String { | |
| return pattern.pattern | |
| } | |
| @objc class func isValid(_ textToValidate: String, with pattern: ValidationPattern) -> Bool { | |
| let validationRegex = pattern.pattern | |
| return self.validate(textToValidate, with: validationRegex) | |
| } | |
| @objc class func isValid(_ textToValidate: String, using customPattern: String) -> Bool { | |
| return self.validate(textToValidate, with: customPattern) | |
| } | |
| //MARK: - private | |
| @objc private class func validate(_ textToValidate: String, with regexPattern: String) -> Bool { | |
| do { | |
| let regex = try NSRegularExpression(pattern: regexPattern) | |
| let nsString = textToValidate as NSString | |
| let results = regex.matches(in: textToValidate, range: NSRange(location: 0, length: nsString.length)) | |
| return !results.isEmpty | |
| } catch let error { | |
| print("invalid regex: \(error.localizedDescription)") | |
| return false | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment