Validating user input is a common task in dynamic iOS and macOS apps. This post presents examples of using regular expressions to validate email, phone number, username, password, and date user inputs in Swift:

  1. Email Regular Expression
    a. Simple Email Regex
    b. Email Validation Example
  2. Phone Number Regular Expression
    a. Simple Phone Number Regex
    b. Phone Number Validation Example
  3. Username Regular Expression
    a. Simple Username Regex
    b. Username Validation Example
  4. Password Regular Expression
    a. Simple Password Regex
    b. Password Validation Example
  5. Date Regular Expression
    a. Simple Date Regex
    b. Date Validation Example

Email Regular Expression

Emails can be validated using a regular expression. Matching the full email address specification requires a complex regular expression. However, for many iOS and macOS applications a simple email regular expression is acceptable.

Simple Email Regex

// One or more characters followed by an "@",
// then one or more characters followed by a ".",
// and finishing with one or more characters
let emailPattern = #"^\S+@\S+\.\S+$"#

// Matching Examples
// user@domain.com
// firstname.lastname-work@domain.com

Email Validation Example

One way to validate emails with regular expressions is the String method range(of:, options:):

// "test@test.com" matches emailPattern,
// so result is a Range<String.Index>
var result = "test@test.com".range(
    of: emailPattern,
    options: .regularExpression
)

let validEmail = (result != nil)

If an iOS or macOS application uses the same regular expression many times, the NSRegularExpression method matches(in:, options:, range:) may be more efficient:

let emailRegex = try! NSRegularExpression(
    pattern: emailPattern,
    options: []
)

let source = "test@test.com"
let sourceRange = NSRange(
    source.startIndex..<source.endIndex,
    in: source
)

// "test@test.com" matches emailPattern,
// so result is a [NSTextCheckingResult]
var result = emailRegex.matches(
    in: source,
    options: [],
    range: sourceRange
)

let validEmail = (result != nil)

Phone Number Regular Expression

Phone numbers can be validated using regular expressions. If an iOS or macOS is localized for customers in different parts of the world, change the regular expression to match regional phone number format conventions.

Simple Phone Number Regex

// 3 numbers, then 3 numbers, then 4 numbers
// The first 3 numbers may be enclosed in (), and either 
// " " or "-" can be used to separate number groups
let phonePattern = #"^\(?\d{3}\)?[ -]?\d{3}[ -]?\d{4}$"#

// Matching Examples
//111-222 3333
//111 222 3333
//(111) 222-3333
//1112223333

The phonePattern can be adapted to validate other phone number formats. The syntax \d{3} matches 3 numbers 123. To match, for example 22-33, the syntax would be \d{2}-\d{2}.

Phone Number Validation Example

One way to validate phone numbers with regular expressions is the String method range(of:, options:):

// "(567)-678 1231" matches emailPattern,
// so result is a Range<String.Index>
var result = "(567)-678 1231".range(
    of: phonePattern,
    options: .regularExpression
)

let validPhoneNumber = (result != nil)

If an iOS or macOS application uses the same regular expression many times, the NSRegularExpression method matches(in:, options:, range:) may be more efficient:

let phoneRegex = try! NSRegularExpression(
    pattern: phonePattern,
    options: []
)

let source = "(567)-678 1231"
let sourceRange = NSRange(
    source.startIndex..<source.endIndex,
    in: source
)

// "(567)-678 1231" matches phonePattern,
// so result is a [NSTextCheckingResult]
var result = phoneRegex.matches(
    in: source,
    options: [],
    range: sourceRange
)

let validPhoneNumber = (result != nil)

Username Regular Expression

Usernames and full names can be validated using regular expressions. If an iOS or macOS is localized for customers in different parts of the world, change the regular expression to accept regional language characters.

Simple Username Regex

// One or more characters, followed by any text,
// then a space, and finally one or more characters.
// This regular expression requires first and last names, 
// while also accepting middle names.
let usernamePattern = #"^[a-zA-Z-]+ ?.* [a-zA-Z-]+$"#

// Matching Examples
// Steve Jobs
// Tim Cook
// Greg Joz Joswiak

Username Validation Example

One way to validate usernames with regular expressions is the String method range(of:, options:):

// "FirstName LastName" matches usernamePattern,
// so result is a Range<String.Index>
var result = "FirstName LastName".range(
    of: usernamePattern,
    options: .regularExpression
)

var validUsername = (result != nil)

If an iOS or macOS application uses the same regular expression many times, the NSRegularExpression method matches(in:, options:, range:) may be more efficient:

let nameRegex = try! NSRegularExpression(
    pattern: usernamePattern,
    options: []
)

let source = "FirstName LastName"
let sourceRange = NSRange(
    source.startIndex..<source.endIndex,
    in: source
)

// "FirstName LastName" matches usernamePattern,
// so result is a [NSTextCheckingResult]
var result = nameRegex.matches(
    in: source,
    options: [],
    range: sourceRange
)

let validUsername = (result != nil)

In addition to username validation, extracting a first and last name from a username is a common task that can be implemented with regular expressions. The article Regular Expression Capture Groups presents examples of using capture groups to extract first and last names.

Password Regular Expression

Password requirements can be validated using regular expressions. Regular expressions are flexible, and can support many different password requirements found in iOS and macOS apps.

Simple Password Regex

The ?= syntax is used to create a "positive look ahead" check in a regular expression. Combining multiple positive look aheads is one way to create a multi-requirement password validation regular expression:

let passwordPattern =
    // At least 8 characters
    #"(?=.{8,})"# +

    // At least one capital letter
    #"(?=.*[A-Z])"# +
        
    // At least one lowercase letter
    #"(?=.*[a-z])"# +
        
    // At least one digit
    #"(?=.*\d)"# +
        
    // At least one special character
    #"(?=.*[ !$%&?._-])"#

Password Validation Example

One way to validate passwords with regular expressions is the String method range(of:, options:):

// "$tr0ngPa$$w0rd" matches passwordPattern,
// so result is a Range<String.Index>
var result = "$tr0ngPa$$w0rd".range(
    of: passwordPattern,
    options: .regularExpression
)

var validPassword = (result != nil)

If an iOS or macOS application uses the same regular expression many times, the NSRegularExpression method matches(in:, options:, range:) may be more efficient:

let passwordRegex = try! NSRegularExpression(
    pattern: passwordPattern,
    options: []
)

let source = "$tr0ngPa$$w0rd"
let sourceRange = NSRange(
    source.startIndex..<source.endIndex,
    in: source
)

// "$tr0ngPa$$w0rd" matches passwordPattern,
// so result is a [NSTextCheckingResult]
var result = passwordRegex.matches(
    in: source,
    options: [],
    range: sourceRange
)

let validPassword = (result != nil)

Date Regular Expression

Date formats can be validated using regular expressions. Change the date regular expression to match the expected date input format of your iOS or macOS application

Simple Date Regex

// 1-2 digits followed by "-" or "/",
// then 1-2 digits followed by "-" or "/",
// finally 4 digits
let datePattern = #"^\d{1,2}[\/-]\d{1,2}[\/-]\d{4}$"#

// Matching Examples
// 1/2/2021
// 02-03-2020

Date Validation Example

One way to validate dates with regular expressions is the String method range(of:, options:):

// "02-3-2020" matches datePattern,
// so result is a Range<String.Index>
var result = "02-3-2020".range(
    of: datePattern,
    options: .regularExpression
)

var validDate = (result != nil)

If an iOS or macOS application uses the same regular expression many times, the NSRegularExpression method matches(in:, options:, range:) may be more efficient:

let dateRegex = try! NSRegularExpression(
    pattern: datePattern,
    options: []
)

let source = "02-3-2020"
let sourceRange = NSRange(
    source.startIndex..<source.endIndex,
    in: source
)

// "02-3-2020" matches datePattern,
// so result is a [NSTextCheckingResult]
var result = dateRegex.matches(
    in: source,
    options: [],
    range: sourceRange
)

let validDate = (result != nil)

In addition to date validation, extracting date components from a date is a common task that can be implemented with regular expressions. The article Regular Expression Capture Groups presents examples of using capture groups to extract date components.

Regular Expressions in Swift

That’s it! By using NSRegularExpression and String.range(of:, options:) you can validate email, phone number, username, password, and date inputs in Swift using regular expressions.