0

I have three text fields called home phone,work phone and mobile phone. i need to do validation and number formatting for these fields. Below shown is the condition.

The home phone and work phone text fields should not accept more than 10 digits and less than eight digits. The fields should accept only numbers. The format of the numbers should be xxxx-xxxx(if 8 digits) xx-xxxx-xxxx(if it is 10 digits)

The Mobile Phone number field should not accept more than 10 digits. The fields should accept only the numbers. The format of the numbers should be xxxx-xxx-xxx

I am not sure how to achieve this. Please help me.

Karthick
  • 382
  • 1
  • 3
  • 23

2 Answers2

1

I think you can achieve this by doing the following:

  1. Capture the text change event in uitextfield. Add the dashes after 4 characters, after 7 characters and so on depending on what format you want.
  2. Use a regular expression to validate the entire string of numbers with dashes. (eg: for xxxx-xxxx format use '[0-9]{4}-[0-9]{4}')
R3D3vil
  • 681
  • 1
  • 9
  • 22
0

Little late but it may help some other one, formatting UITextfield text in format XXX-XXX-XXXX

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

        var number = textField.text  as NSString? ?? ""
        number = number.replacingCharacters(in: range, with: string) as NSString
        number = number.replacingOccurrences(of: "-", with: "") as NSString

        if (number.length > 10) {
            return false;
        }
        self.resetBtnState(numberLength: number.length)
        var groupSize = 3
        let separator = "-"
        if string.characters.count == 0 {
            groupSize = 5
        }
        let numformatter = NumberFormatter()
        numformatter.groupingSeparator = separator
        numformatter.groupingSize = groupSize
        numformatter.usesGroupingSeparator = true
        numformatter.secondaryGroupingSize = 3
        if var number = textField.text, string != "" {
            number = number.replacingOccurrences(of: separator, with: "")
            if let doubleVal = Double(number) {
                let requiredString = numformatter.string(from: NSNumber.init(value: doubleVal))
                textField.text = requiredString
            }
        }
        return true
    }
Alok Srivastava
  • 197
  • 1
  • 3
  • 18