Here's an interesting String extension to check email syntax I gleaned from Stack Overflow:
extension String {
public var isEmail: Bool {
let dataDetector = try? NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue)
let firstMatch = dataDetector?.firstMatch(in: self, options: .reportCompletion, range: NSRange(location: 0, length: length))
return (firstMatch?.range.location != NSNotFound && firstMatch?.url?.scheme == "mailto")
}
public var length: IndexDistance {
return self.characters.count
}
}
@objc func handleTextInputChange(_ sender: UITextField){
guard let email = emailTextField.text, let username = usernameTextField.text, let password = passwordTextField.text else { return }
let isEmailValid = email.isEmail // valid email syntax?
let isUsernameValid = username.length > 0 // length is same as characters.count
let isPasswordValid = password.length > 0
let isFormValid = isEmailValid && isUsernameValid && isPasswordValid
signUpButton.isEnabled = isFormValid
signUpButton.backgroundColor = signUpButton.isEnabled ? UIColor(r: 17, g: 154, b: 237) : UIColor(r: 149, g: 204, b: 244)
}
I like to put @objc on Objective-C selector handlers, making them easy to spot.
(I did this when a earlier version of Xcode complained about marking the handler private.)
The parameter, _ sender: UITextField is not needed, but I can tell which text field triggered this handler by setting the
tag property for each text field, e.g., in the block closure set up -
let textField = UITextField()
textField.tag = 0 // or 1, 2 or something...
textField.addTarget(self, action: #selector(handleTextInputChange(_:)), for: .editingChanged)
Thanks