In this tutorial, I am going to share how to validate an email address in Swift programming. This is a very basic program in Swift programming language. If you are Swift beginners or want to start learning Swift programming language, then this program will help you to understand the basic Swift programming.
Copy the below program and create a file named “SwitchProgramExample.swift” and execute it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 | 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 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) } } |
If you like FreeWebMentor and you would like to contribute, you can write an article and mail your article to [email protected] Your article will appear on the FreeWebMentor main page and help other developers.