Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I validate TextFields in an UIAlertController?

Tags:

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

I need it to prevent the user from clicking "Save" unless both fields are entered.

Here is my code so far:

@IBAction func btnStart(sender: AnyObject) {
    var alert = UIAlertController(title: "New user",
        message: "Add a new user",
        preferredStyle: .Alert)

    let saveAction = UIAlertAction(title: "Save",
        style: .Default) { (action: UIAlertAction!) -> Void in

            self.textFieldName = alert.textFields![0] as UITextField
            self.textFieldEmail = alert.textFields![1] as UITextField
            self.saveUser(self.textFieldName.text, email: self.textFieldEmail.text)
            self.tableView.reloadData()
    }

    saveAction.enabled = false

    let cancelAction = UIAlertAction(title: "Cancel",
        style: .Default) { (action: UIAlertAction!) -> Void in
    }

    alert.addTextFieldWithConfigurationHandler {
        (textFieldName: UITextField!) in
        textFieldName.placeholder = "Enter full name"
    }

    alert.addTextFieldWithConfigurationHandler {
        (textFieldEmail: UITextField!) in
        textFieldEmail.placeholder = "Enter valid email adress"
        textFieldEmail.keyboardType = .EmailAddress

    }
    alert.addAction(saveAction)
    alert.addAction(cancelAction)

    presentViewController(alert,
        animated: true,
        completion: nil)
}

This is my function for validating the Email field:

func isValidEmail(testStr:String) -> Bool {
    let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"

    if let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx) {
        return emailTest.evaluateWithObject(testStr)
    }
    return false
}
like image 854
MarkoDeveloper Avatar asked Jun 02 '15 12:06

MarkoDeveloper


2 Answers

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)
}

enter image description here

like image 174
Scott Gardner Avatar answered Oct 23 '22 06:10

Scott Gardner


Most elegant way is to use

NotificationCenter.default.addObserver(forName: NSNotification.Name.UITextFieldTextDidChange...

Swift 3.0 example

let alert = UIAlertController(title: nil, message: nil, preferredStyle: .alert)
    alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
    let saveAction = UIAlertAction(title:"Save", style: .destructive, handler: { (action) -> Void in

    })
    alert.addAction(saveAction)
    alert.addTextField(configurationHandler: { (textField) in
        textField.placeholder = "Enter something"
        NotificationCenter.default.addObserver(forName: NSNotification.Name.UITextFieldTextDidChange, object: textField, queue: OperationQueue.main) { (notification) in
            saveAction.isEnabled = textField.text!.length > 0
        }
    })
    present(alert, animated: true, completion: nil)
like image 20
imike Avatar answered Oct 23 '22 06:10

imike