chronotruck / FlagPhoneNumber

A formatted phone number UITextField with country flag picker.
Apache License 2.0
437 stars 317 forks source link

Pasted number is invalid #146

Open netgfx opened 4 years ago

netgfx commented 4 years ago

Describe the bug When I'm trying to paste a valid number like: +1-202-555-0187 it returns invalid, however if I paste this: 202-555-0187 or even 2025550187, it returns as valid.

To Reproduce Steps to reproduce the behavior:

  1. Paste number on input: +1-202-555-0187
  2. Check validity
  3. See error

Expected behavior Since the library is smart enough to remove the +1 correctly, it should also set the number as valid.

Smartphone (please complete the following information):

Additional context The flag is always set to US when trying.

netgfx commented 4 years ago

One solution that I found is to listen to:

 phoneInputView.addTarget(self, action: #selector(updateTextField), for: .editingChanged)

and then async trigger a .editingChanged event, which will correctly re-format the input value and set it as valid

@objc func updateTextField() {
        DispatchQueue.main.async {
         //check if value is already valid, then format and set it to input again
            if self.phoneInputView.getFormattedPhoneNumber(format: .National) != nil {
                self.phoneInputView.text = self.phoneInputView.getFormattedPhoneNumber(format: .National)
            }
            else {
          /* if not valid, re-trigger the event to re-check it, if it is indeed invalid nothing changes, if it is valid (from paste) then it is formatted and set as valid */
                self.phoneInputView.sendActions(for: .editingChanged)
            }
        }
    }
anees17861 commented 4 years ago

I have created a PR(#155) for this issue. The changes are very small and doesn't require client side code updation

sameeh0946 commented 4 years ago

I found a simple fix for this by resetting the input in the Delegate when phoneNumberIsvalid returns false

    func fpnDidValidatePhoneNumber(textField: FPNTextField, isValid: Bool) {
        if isValid == true {
            DispatchQueue.main.async {
                self.isValid = true
            }
        }
        else {
            DispatchQueue.main.async {
                self.isValid = false
                let input:String = self.phoneNumberTextField.text!    //Here
                self.phoneNumberTextField.set(phoneNumber: input)
            }
        }
    }