neoneye/SwiftyFORM

Format elements like Phone Number

justdan0227 opened this issue · 3 comments

Is there a way to add formatting rules for fields like phone numbers to be (xxx) xxx-xxxx ?

Can you capture the textfield delegate to so something like is posted in stackoverflow for phone number formatting?

/// mask example: +X (XXX) XXX-XXXX`
func format(with mask: String, phone: String) -> String {
let numbers = phone.replacingOccurrences(of: "[^0-9]", with: "", options: .regularExpression)
var result = ""
var index = numbers.startIndex // numbers iterator

// iterate over the mask characters until the iterator of numbers ends
for ch in mask where index < numbers.endIndex {
    if ch == "X" {
        // mask requires a number in this place, so take the next one
        result.append(numbers[index])

        // move numbers iterator to the next index
        index = numbers.index(after: index)

    } else {
        result.append(ch) // just append a mask character
    }
}
return result

}
Call the above function from the UITextField delegate method:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let text = textField.text else { return false }
let newString = (text as NSString).replacingCharacters(in: range, with: string)
textField.text = format(with: "+X (XXX) XXX-XXXX", phone: newString)
return false
}
So, that is work better.

"" => ""
"0" => "+0"
"412" => "+4 (12"
"12345678901" => "+1 (234) 567-8901"
"a1_b2-c3=d4 e5&f6|g7h8" => "+1 (234) 567-8"`

I can't remember. I think it's difficult to do live-updates with the UIKit textfield as the user types in text. Phone numbers are tricky and localized. Maybe UIKit textfield already has support for phone number formatting.

Ideas to try out:

  • first make it work with the UIKit textfield as a standalone app.
  • next adapt the textfield code to a SwiftyFORM customcell.
  • Or modify the SwiftyFORM textfield in such way that it can do the formatting.

@neoneye Thanks.. will try and report back