Prevent Text Field from containing 2 decimal points in Swift

Hi all.

I'm developing a savings goal app, and there is a screen that allows users to input data about a new goal.

I want to make sure that the user cannot input 2 decimal points on the saving amount text field otherwise the app will crash.

Does anybody have a solution to this?

Here's my code:

    @IBAction func createSaving(_ sender: Any) {

        if(savingTitleTxt.text!.isEmpty){

            self.view.makeToast("Error. Please specify title.", duration: 2.0, position: .bottom)

            return

        }

        

        if(savingAmountTxt.text!.isEmpty || savingAmountTxt.text!.contains(" ")){

            self.view.makeToast("Error. Please specify a valid goal amount.", duration: 2.0, position: .bottom)

            return

        }

        

        var tempList:[SavingItem] = getData()

        

        tempList.append(SavingItem(title: savingTitleTxt!.text!, image: savingImage!.image!.pngData()!, goal: Double(savingAmountTxt!.text!)!, saved: 0))

        

        saveData(list: tempList)

        

        self.view.makeToast("Success", duration: 2.0, position: .bottom)
Answered by ForumsContributor in
Accepted Answer

Declare that the class conforms to UITextFieldDelegate

Use the func:

     func textFieldDidChangeSelection(_ textField: UITextField) { }

to test there are not 2 decimal points (and maybe test that you only have digits ?)

Code should be like this (I assume there is only one textField in your view, otherwise you have to test that textField is the correct one):

    func textFieldDidChangeSelection(_ textField: UITextField) {
          
          if let typedText = textField.text {       // What have we typed in ?
               var dotCount = 0
               for c in typedText {  // count dot or comma     
                   if String(c) == "." || String(c) == "," {  dotCount += 1  }
              }
               if dotCount >= 2 {    // remove last typed
                    textField.text = String(typedText.dropLast())
              }
          }

     }
Prevent Text Field from containing 2 decimal points in Swift
 
 
Q