How do I validate TextFields in an UIAlertController?

后端 未结 10 2294
不思量自难忘°
不思量自难忘° 2020-12-14 08:54

Can anyone tell me how to validate UITextFields inside of a UIAlertController?

I need it to prevent the user from clicking \"Save\" unless

10条回答
  •  星月不相逢
    2020-12-14 09:02

    This can be done by extending UIAlertViewController:

    extension UIAlertController {
    
        func isValidEmail(_ email: String) -> Bool {
            return email.characters.count > 0 && NSPredicate(format: "self matches %@", "[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,64}").evaluate(with: email)
        }
    
        func isValidPassword(_ password: String) -> Bool {
            return password.characters.count > 4 && password.rangeOfCharacter(from: .whitespacesAndNewlines) == nil
        }
    
        func textDidChangeInLoginAlert() {
            if let email = textFields?[0].text,
                let password = textFields?[1].text,
                let action = actions.last {
                action.isEnabled = isValidEmail(email) && isValidPassword(password)
            }
        }
    }
    
    // ViewController
    override func viewDidLoad() {
        super.viewDidLoad()
    
        let alert = UIAlertController(title: "Please Log In", message: nil, preferredStyle: .alert)
    
        alert.addTextField {
            $0.placeholder = "Email"
            $0.addTarget(alert, action: #selector(alert.textDidChangeInLoginAlert), for: .editingChanged)
        }
    
        alert.addTextField {
            $0.placeholder = "Password"
            $0.isSecureTextEntry = true
            $0.addTarget(alert, action: #selector(alert. textDidChangeInLoginAlert), for: .editingChanged)
        }
    
        alert.addAction(UIAlertAction(title: "Cancel", style: .cancel))
    
        let loginAction = UIAlertAction(title: "Submit", style: .default) { [unowned self] _ in
            guard let email = alert.textFields?[0].text,
                let password = alert.textFields?[1].text
                else { return } // Should never happen
    
            // Perform login action
        }
    
        loginAction.isEnabled = false
        alert.addAction(loginAction)
        present(alert, animated: true)
    }
    

提交回复
热议问题