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

Replies

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 ""

  • This does not help, as this event gets called only after the text is already pasted.

Add a Comment