Skip to content

Instantly share code, notes, and snippets.

@deathlezz
Last active July 31, 2021 13:26
Show Gist options
  • Save deathlezz/3d9fb37434e1018cf056d6c25b9de39f to your computer and use it in GitHub Desktop.
Save deathlezz/3d9fb37434e1018cf056d6c25b9de39f to your computer and use it in GitHub Desktop.
Check validation by Regular Expression(regex) in Swift 5.
//
// Regular Expression (regex)
//
// Check validation by regex
//
import Foundation
// Date
let date = "27-07-1999 10:41:12"
// Check date's format (dd-MM-yyyy HH:mm:ss) and validation (e.g. month = 1...12, day = 1...31, year = 1900...2099 etc.)
let dateRegex = "^(0?[1-9]|[12][0-9]|3[01])[-/.](0?[1-9]|1[012])[-/.](19|20)\\d\\d ([01]?[0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$"
let dateTest = NSPredicate(format: "SELF MATCHES %@", dateRegex)
let dateResult = dateTest.evaluate(with: date)
print(dateResult) // true
// Email
let email = "jerry.mouse@gmail.com"
// Check email format (user@domain.com or firstname.lastname@domain.com)
let emailRegex = #"^\S+@\S+\.\S+$"#
let emailTest = NSPredicate(format: "SELF MATCHES %@", emailRegex)
let emailResult = emailTest.evaluate(with: email)
print(emailResult) // true
// Phone number
let phone = "(111) 222-3333"
// Check phone number format (e.g. 111-222-333 or (111) 222 3333 etc.)
let phoneRegex = #"^\(?\d{3}\)?[ -]?\d{3}[ -]?\d{3,4}$"#
let phoneTest = NSPredicate(format: "SELF MATCHES %@", phoneRegex)
let phoneResult = phoneTest.evaluate(with: phone)
print(phoneResult) // true
// Username
let username = "Jerry The Mouse"
// Check username format (e.g. Jerry The Mouse or Steve Jobs)
let usernameRegex = #"^[a-zA-Z-]+ ?.* [a-zA-Z-]+$"#
let usernameTest = NSPredicate(format: "SELF MATCHES %@", usernameRegex)
let usernameResult = usernameTest.evaluate(with: username)
print(usernameResult) // true
// Password
let password = "AAaaa11$"
// Check password format (8-16 characters, 2 capital letters, 2 lowercase letters, 2 digits and 1 special character)
let passwordRegex = #"^(?=.*[A-Z].*[A-Z])(?=.*[a-z].*[a-z])(?=.*\d.*\d)(?=.*[!$%&@#*]).{8,16}$"#
let passwordTest = NSPredicate(format: "SELF MATCHES %@", passwordRegex)
let passwordResult = passwordTest.evaluate(with: password)
print(passwordResult) // true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment