Nikita Ignatev
Nikita Ignatev

Reputation: 25

Validating text inputs in swift

My code doesn't work, can you point out whats wrong. I am trying to validate user input in SNameInput, error label should change it's text when the input is not valid and STitle should change it's text when user is done typing in SNameInput and it is valid, thanks!

func textFieldDidChange(SNameInput: UITextField) {
        let d = ""
        if (SNameInput.isEqual(d)||(SNameInput.text?.characters.count)! >= 21) {
            errorLabel.text = "Name has to be a t least 1 character and not longer than 20"}
        else{  errorLabel.text = ""
            Stitle.text = SNameInput.text}
    }

Upvotes: 1

Views: 2779

Answers (1)

Lawliet
Lawliet

Reputation: 3499

Possibility: you didn't add editingDidEnd action to your SNameInput text field.

editingDidEnd: A touch ending an editing session in a UITextField object by leaving its bounds.

override func viewDidLoad() {
    super.viewDidLoad()

    SNameInput.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingDidEnd)
}

@IBAction func textFieldDidChange(_ sender: UITextField) {
    guard let string = sender.text else { return }

    if (string.isEmpty || string.characters.count >= 21) {
        errorLabel.text = "Name has to be a t least 1 character and not longer than 20"
    }
    else{
        errorLabel.text = ""
        Stitle.text = string
    }
}

Upvotes: 2

Related Questions