neoneye / SwiftyFORM

iOS framework for creating forms
MIT License
1.07k stars 86 forks source link

Format elements like Phone Number #54

Open justdan0227 opened 3 years ago

justdan0227 commented 3 years ago

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

justdan0227 commented 3 years ago

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

neoneye commented 3 years ago

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:

justdan0227 commented 3 years ago

@neoneye Thanks.. will try and report back