Disable AutoFill option in UITextField or have control over the text which is being pasted using that option.

I have form fields in an app, I have some validations to perform like phone number should only have digits and not alphabets, however when user uses AutoFill option doing long press on textfield they have option to choose Contacts and they can tap on name and it will paste alphabets in my Phone number field, that behavior I don't want as my validations will not be fulfilled. There are no callbacks to detect and prevent that text from being pasted.

In shouldChangeCharactersIn delegate method even if I return false for that paste event it ignores that and forcefully it gets pasted.

Please help how to tackle such scenarios to perform above mentioned validations.

Thanks

Could you show the code, to see exactly what you are doing ?

I would do as follows:

  • declare an IBAction
@IBAction func editingTestField(_ sender: UITextField) {

          if conditionOKl {
               print("OK")
          } else {  // Then, discard the change
               sender.text = ""
          }
}
  • In Connections inspector, connect the TextField 'Editing changed' 'sent events' to this IBAction:

This clears the complete TextField. If you want to preserve content before cancelling autoFill, you should save the current content of TextField and use it instead of ""

Faced with this problem, it's not clear how to remove the action. However, you can check the inserted text. If the content includes anything other than numbers, it won't appear in the text field.


func textFieldDidChangeSelection(_ textField: UITextField) {
        if let text = textField.text {
            let filteredText = text.filter { $0.isNumber }
            if text != filteredText {
                textField.text = filteredText
            }
        }
    }

Disable AutoFill option in UITextField or have control over the text which is being pasted using that option.
 
 
Q