an email validation field in swift

To validate an email address in Swift, you can use Regular Expressions (regex). Here's an example of how to do it in a UITextField:

main.swift
func isValidEmail(_ email: String) -> Bool {
    // regex pattern for email validation
    let emailRegex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
    let emailPredicate = NSPredicate(format: "SELF MATCHES %@", emailRegex)
    return emailPredicate.evaluate(with: email)
}

// Using the function in a UITextField
let emailTextField = UITextField()
emailTextField.keyboardType = .emailAddress

// Add a target to the text field, for example in viewDidLoad()
emailTextField.addTarget(self, action: #selector(emailChanged), for: .editingChanged)

// Implement the action function
@objc func emailChanged() {
    if isValidEmail(emailTextField.text ?? "") {
        // email is valid, do something
    } else {
        // email is not valid, show error message or disable button, etc.
    }
}
802 chars
23 lines

In this example, we define a function called isValidEmail that takes an email address as input and uses regex to validate it. We then add a target to a UITextField that listens for changes in the text field, and calls the emailChanged function. In emailChanged, we check if the text in the UITextField is valid according to our isValidEmail function, and we handle the validation result accordingly.

gistlibby LogSnag