title: Autoformat UITextfield in phone number format XXX-XXX-XXXX in iOS
body: <p>I'm trying to autoformat my textfield in the format XXX-XXX-XXXX. The rules are that it should be in the format as mentioned and the first number should be greater than zero and should be of max 10 digits, the regex for this is already added in my function. Below are the methods I'm using</p>
  
  <pre><code>@IBAction func validateAction(_ sender: Any) {
          guard let phoneNumber = phoneNumber.text else {return }
          if validatePhoneNumber(phoneNumber: phoneNumber) {
              errorMessage.text = "Validation successful"
          } else {
              errorMessage.text = "Validation failed"
          }
  
      }
  
      func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -&gt; Bool {
  
              guard let currentText = textField.text as NSString? else {return true}
              let textString = currentText.replacingCharacters(in: range, with: string)
              if textField == phoneNumber {
                  return textField.updatePhoneNumber(string, textString)
              }else{
                  return true
              }
      }
  
      func validatePhoneNumber(phoneNumber: String) -&gt; Bool {
          let phoneRegex: String = "^[2-9]\\d{2}-\\d{3}-\\d{4}$"
          return NSPredicate(format: "SELF MATCHES %@", phoneRegex).evaluate(with: phoneNumber)
      }
  
  extension UITextField {
  
      func updatePhoneNumber(_ replacementString: String?, _ textString: String?) -&gt; Bool {
          guard let textCount = textString?.count else {return true}
          guard let currentString = self.text else {return true}
          if replacementString == "" {
              return true
          } else if textCount == 4 {
              self.text =  currentString + "-"
          } else if textCount == 8 {
              self.text = currentString + "-"
          } else if textCount &gt; 12 || replacementString == " " {
              return false
          }
          return true
      }
  
  }
  </code></pre>
  
  <p>This works to some extent, now the issue is, user can manually intervene and disrupt the format for eg: if I entered, 234-567-8990, user can place the cursor just before 5 and backspace and type in at the end or between like 567-89900000 or 234567-8990. By validating the regular expression it will give an error but I want to re-adjust the format as user types in. For eg: in the earlier scenario if the user is on cursor before 5 and backspaces it should not remove the dash (-) but just removes 4 and re-adjust format like 235-678-990. Is there any simple way to do this? Any help is appreciated</p>