Email Address Validation in Swift

With this blog post I am going to share with you how to do email address validation with a simple regular expression in Swift. The example is simplified and does not check for all possible variations of email addresses but you can improve it buy enhancing the regular expression used. Although, if used as is, it should cover 99% of all regular email address formats.

The video tutorial will cover:

  • Create a very simple user registration form,
  • Read provided user email address when Sign up button is tapped,
  • Use Swift regular expressions validate provided email address,
  • Display Alert message dialog if provided email address is not valid.

 

Validate Email Address in Swift Video Tutorial

Email Address Validation Code Example in Swift

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var emailAddressTextField: UITextField!
    @IBOutlet weak var passwordTextField: UITextField!
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func signupButtonTapped(_ sender: AnyObject) {
        let providedEmailAddress = emailAddressTextField.text
        
        let isEmailAddressValid = isValidEmailAddress(emailAddressString: providedEmailAddress!)
        
        if isEmailAddressValid
        {
            print("Email address is valid")
        } else {
            print("Email address is not valid")
            displayAlertMessage(messageToDisplay: "Email address is not valid")
        }
        
    }

    
    func isValidEmailAddress(emailAddressString: String) -> Bool {
        
        var returnValue = true
        let emailRegEx = "[A-Z0-9a-z.-_]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,3}"
        
        do {
            let regex = try NSRegularExpression(pattern: emailRegEx)
            let nsString = emailAddressString as NSString
            let results = regex.matches(in: emailAddressString, range: NSRange(location: 0, length: nsString.length))
            
            if results.count == 0
            {
                returnValue = false
            }
            
        } catch let error as NSError {
            print("invalid regex: \(error.localizedDescription)")
            returnValue = false
        }
        
        return  returnValue
    }
    
    func displayAlertMessage(messageToDisplay: String)
    {
        let alertController = UIAlertController(title: "Alert", message: messageToDisplay, preferredStyle: .alert)
        
        let OKAction = UIAlertAction(title: "OK", style: .default) { (action:UIAlertAction!) in
            
            // Code in this block will trigger when OK button tapped.
            print("Ok button tapped");
            
        }
        
        alertController.addAction(OKAction)
        
        self.present(alertController, animated: true, completion:nil)
    }
    
    
}

I hope this short blog post and a video tutorial was helpful to you! I publish short Swift video tutorials every week and I publish different Swift code examples almost every day. If you like to be notified when a new video tutorial gets published, please subscribe to my blog and follow me on social network of your choice below for daily Swift code examples updates.

Twitter: @SwiftVideoBlog
Google Plus: https://plus.google.com/+SergeyKargopolov/posts
Facebook: Swift Developer Blog on Facebook

Happy learning!