Author Topic: How to validate an email address in Swift  (Read 11344 times)

kjmcneish

  • Administrator
  • *****
  • Posts: 719
    • View Profile
How to validate an email address in Swift
« on: May 31, 2015, 11:55:21 AM »
Here is a class that uses regular expressions to validate email addresses:

Code: [Select]
public class Email {
   
    public static var stricterFilter = true // Discussion http://blog.logichigh.com/2010/09/02/validating-an-e-mail-address/
   
    // Test if the specified email address is valid
    public static func isEmailValid(email: String) -> Bool {
       
        var filterString: String
       
        if Email.stricterFilter {
            // Strict filter string
            filterString = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"
        }
        else {
            // lax filter string
            filterString = ".+@.+\\.[A-Za-z]{2}[A-Za-z]*"
        }
       
        let emailTest = NSPredicate(format: "SELF MATCHES %@", filterString)

return emailTest.evaluateWithObject(email)
    }
}

To use this method:

Code: [Select]
let isValid = Email.isEmailValid("myemail@me.com")

All the best!
Kevin McNeish
Author of Learn to Code in Swift: https://itunes.apple.com/us/book/learn-to-code-in-swift/id942956811?mt=11

« Last Edit: September 26, 2015, 08:35:51 AM by kjmcneish »