how to do validation of a UITextField, while still being edited

If you want to add validation to an instance of UITextField, while editing is still going on, there are a few things you need to do.

Step 1:

Make the viewController adopts UITextFieldDelegate in the class declaration

e.g. class myViewController: UIViewController, UITextFieldDelegate {…}

Step 2:

Set the viewController as the delegate for each of your UITextFields, e.g. in the viewController’s viewDidLoad() function. ‘self’ refers to the viewController.

e.g. myTextField.delegate = self

Step 3:

You need to include the following optional delegate function within your viewController class:

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

The important thing to note is that you can’t just check if the UITextField.text is nil or empty when unwrapped, because that won’t work if the UITextField is currently being edited. For that you need to check the UITextField.text + the replacementString.


Note: Since UITextField.text can be nil, safer to set a variable using the nil coalescing operator, then concatonate with the string

e.g. let currentTextInTextField = textField.text ?? “”

then you can do your validation against (currentTextInTextField+string)

Step 4:

return false if your validation fails, or true if it succeeds.

Leave a Reply

Your email address will not be published. Required fields are marked *