Email And Password Validations In iOS/Swift 3

Email And Password Validations In iOS/Swift 3

Hi, In this post, We'll learn about two of most commonly used validations in iOS applications. Validations are almost required in each and every iOS app. So, its good to learn about how to apply these validations in iOS. Through this post, I'll guide you how you can create your own email and password validators for your next iOS app. I am using Xcode 8 and Swift 3 for this tutorial.
So, without any further explanation, let's jump into the coding part..
1. Email Validation:

Function for Email Validations

    func isValidEmail(emailStr: String?) -> Bool {
        guard emailStr != nil else {
            
            return false
        }
        
        let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"
        
        let emailPred = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
        return emailPred.evaluate(with: emailStr)
    }

Here, our email validator basically checks for whether there's
  1. Some text before the @
  2. Some text after the @
  3. Atleast 2 characters after a . (dot)

You can use this function to apply validations on email inputs of your iOS apps. Now, let's see how to use this function.

How to use above created isValidEmail function to validate any email:


        if isValidEmail(emailStr: "bhanu.partap20@gmail.com"){

            print("valid email")

        }

        else {

            print("Invalid email")

        }

2. Password Validation:

Function for Password Format Validator


    func isValidPassword(testPwd : String?) -> Bool{

        guard testPwd != nil else {

            return false

        }

        let passwordPred = NSPredicate(format: "SELF MATCHES %@", "^(?=.*[A-Z])(?=.*[!@#$&*])(?=.*[0-9])(?=.*[a-z]).{8,}$")

        return passwordPred.evaluate(with: testPwd)
    }

Password Regex Explanation
  1. ^              Start Anchor
  2. (?=.*[A-Z])    Atleast one upper case letter
  3. (?=.*[!@#$&*]) Atleast one special character
  4. (?=.*[0-9])    Atleast one digit
  5. (?=.*[a-z])    Atleast one lower case letter
  6. {8,}           Password length must be equal to or greater than 8
  7. $              End Anchor
By using these validators you can ensure the valid email and password inputs for your iOS applications. You can also change or update these regex in both the email and password functions as per your own requirements. 

Let me know if you're having any issue or doubt in any of the above explained validations. I'll try to clear your doubts with best of my knowledge. 

Thanks for your time. Keep coding.. 👨‍💻

Comments

Popular posts from this blog

PayPal Integration In iOS Applications | Payment Gateways iOS/Swift

MacBook Magic: Exploring the Enchanting World of Apple's Laptops

Convert Swift Code To Kotlin Using SwiftKotlin Mac Tool