Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format inputed digits to US phone number to format (###) ###-####

I used this code but the issue I am having is it does not work if texfield is empty (index out of bounds) and the other issue if the user does not change the phonenumber and hit Save button it will execute the code again and insert the "((" and "--".

Any ideas about what I can do?

var stringts: NSMutableString = self.ts.text
stringts.insertString("(", atIndex: 0)
stringts.insertString(")", atIndex: 4)
stringts.insertString("-", atIndex: 5)
stringts.insertString("-", atIndex: 9)
self.ts.text = stringts
like image 507
Yaroslav Dukal Avatar asked Mar 12 '23 17:03

Yaroslav Dukal


1 Answers

You can validate the input while entering from the user. Use the UITextFieldDelgate to do so:

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

    let str = (textField.text! as NSString).stringByReplacingCharactersInRange(range, withString: string)

    if textField == txtFieldPhoneNumber{

        return checkEnglishPhoneNumberFormat(string, str: str)

    }else{

        return true
    }
}

Function to validate the input:

func checkEnglishPhoneNumberFormat(string: String?, str: String?) -> Bool{

    if string == ""{ //BackSpace

        return true

    }else if str!.characters.count < 3{

        if str!.characters.count == 1{

            txtFieldPhoneNumber.text = "("
        }

    }else if str!.characters.count == 5{

        txtFieldPhoneNumber.text = txtFieldPhoneNumber.text! + ") "

    }else if str!.characters.count == 10{

        txtFieldPhoneNumber.text = txtFieldPhoneNumber.text! + "-"

    }else if str!.characters.count > 14{

        return false
    }

    return true
}

Hope this helps!

like image 152
Sohil R. Memon Avatar answered Mar 25 '23 08:03

Sohil R. Memon