Skip to content

iOS/Swift Validate Email and Password Format

Validation for Email and Password

Validation for Email and PasswordHere’s a couple of quick functions I use in a few forms in different projects.

They’re pretty common and can be found other places. I based these on various things I’ve found online. So, like most things, I can’t take 100% credit but we all learned things from somewhere.

The first is an email validator. Basically it just verfies that:

  1. There’s some text before the @
  2. There’s some text after the @
  3. There’s at least 2 alpha characters after a .
import Foundation
// validate an email for the right format
func isValidEmail(email:String?) -> Bool {
    
    guard email != nil else { return false }
    
    let regEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"
    
    let pred = NSPredicate(format:"SELF MATCHES %@", regEx)
    return pred.evaluate(with: email)
}

The second is a password format validator. It basically checks for…

  1. There’s at least one uppercase letter
  2. There’s at least one lowercase letter
  3. There’s at least one numeric digit
  4. The text is at least 8 characters long
func isValidPassword(testStr:String?) -> Bool {
    guard testStr != nil else { return false }

    // at least one uppercase, 
    // at least one digit 
    // at least one lowercase
    // 8 characters total
    let passwordTest = NSPredicate(format: "SELF MATCHES %@", "(?=.*[A-Z])(?=.*[0-9])(?=.*[a-z]).{8,}")
    return passwordTest.evaluate(with: testStr)
}

In both cases, you can see the regular expression format and change it as needed. For example, the email validator use to require 3 characters after the . for things like .com, .net, etc. but now there are many domains with 2 characters like .co – technically there always has been but many examples online required 3.

My first email address was Swedish and had .se – that through a lot of people off.