Introduction to email address validation in swift
In this tutorial, we will learn how to add email address validation in swift4. We will use NSPredicate with regex to validate email of format “firstname.lastname@example.org”. Also, how to validate an empty UITextField in swift using guard statement. Let us jump to the tutorial and learn how to validate email address and check for empty UITextFields in swift.
Steps to add email validation in swift
Creating user interface for the app
Step 1: Open up Xcode and select “Single View App” template, name it “ValidationsAndEmailValidation“.
Step 2: Open “Main.storyboard” as we are going to create user interface as shown in given below picture
Step 3: Drag UILabel to view as we want to display validation message to user if inputs failed to validate email address or if UITextFields are empty i.e empty UITextField validation and add constraints as shown below
Step 4: Drag UITextField for Email address to be entered by user and add constraints as shown below
Step 5: Drag UITextField for password to be entered by user and add constraints as shown below
Step 6: Drag UIButton so that we can validate the values inputted by user when he tap on button and add constraints as shown below
Step 7: As of now we are done with our user interface design and if you run your app, you will see its nicely comes up on iPhone simulator screen.
Coding for email validation
Step 8: Open “ViewController.swift” and create IBOutlet for two UITextFields, UILabel and IBAction for our UIButton.
Step 9: Open “Main.storyboard” and connect IBOutlets created in step 8 to UILabel and UITextFields. Connect IBAction to “touchupinside” event of UIButton.
Step 10: Now in viewDidLoad function set “lblValidationMessage” to hidden as we did not want to show any message until user tap on UIButton.
Step 12: In our “loginUser” IBAction, we will call the above script and validate our email typed in “txtEmail” UITextField. Also we will use “guard” statement to check whether our UITextFields contains any value or are empty. If empty then we will show validation message in “lblValidationMessage” UILabel.
Step 13: Run your app and you will see the validations are working.
Where to go from here:
We learned how to validate email address in swift. Also we learned to validate empty UITextField using guard statement in swift. Download the source code from here.