Search code examples
iosswiftskyfloatinglabeltextfield

Swift: check user input count to proceed


I have a field that takes a verification code sent through SMS. The code sent to all users is 4 digit numeric code. I want the user to type the code, and upon entering the 4th digit, the code is checked automatically (no button click required) and print correct to console if matches expected value. If not matching, then print Incorrect to console (console used here for printing purposes).

Assuming the code I have (fixed for purposes of testing) is 1234, below is my attempt that is not working as expected:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

        if let text = textField.text {

            if let floatingLabelTextField = textField as? SkyFloatingLabelTextField {
                if(text.characters.count > 4) {
                    floatingLabelTextField.errorMessage = "code is invalid"
                }
                else {
                    // The error message will only disappear when we reset it to nil or empty string
                    floatingLabelTextField.errorMessage = ""
                    let smsInputCode = Int(self.verificationTextField.text!)
                    if(smsInputCode == self.smsSampleCode)
                    {
                        print("Correct Code")
                    }else{
                        print("Incorrect Code")
                    }
                }
            }
        }
        return true
    }

The above code prints "incorrect" 4 times as I am typing the digits then shows correct code only after I click on tab bar on keyboard (not auto detection).

Appreciate your help.


Solution

  • I write a demo you can refer to:

    In the ViewController:

    import UIKit
    
    class ViewController: UIViewController {
    
        @IBOutlet weak var textField: UITextField!
    
        @IBOutlet weak var label: UILabel!
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            textField.addTarget(self, action: #selector(textFieldAction), for: .editingChanged)
    
    
        }
    
        func textFieldAction() {
    
            if (textField.text?.characters.count)! > 4 {
    
                let lengh = textField.text?.characters.count
    
                let str:NSString = textField.text! as NSString
    
                textField.text = str.substring(to: lengh! - 1)
            }
    
            if textField.text == "1234" {
                label.text = "valid"
            }else {
                label.text = "invalid"
            }
    
        }
    
    }
    

    The result:

    enter image description here