28 Jan 2018

Email address validation in swift


Email address validation in swift

Introduction to email address validation in swift

                 In this tutorial we will learn how to validate email address in swift4. We will use NSPredicate with regex to validate email of format "[email protected]". Also we will learn how to validate an empty UITextField in swift using guard statement. Let us jump to the tutorial and learn how to validate email address in swift and check for empty UITextFields in swift.

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

Email validation in swift

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

Email address validation in swift

Step 4: Drag UITextField for Email address to be entered by user and add constraints as shown below

Email address validation in swift

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

email validation in swift

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.

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 use tap on UIButton.




Step 11: We will create another function named "isValidEmail", accepting email as parameter and return TRUE or FALSE based upon email validation using regex and NSPredicate.



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.

Complete Code:

Where to go from here:

In this tutorial, 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. If you have any question then please feel free to ask. Thanks

No comments:

Post a Comment