-2

I have a textfield of type decimalPad. However, if the user types ".", "..", ... my DB will get an error.

If uesr enters the above values, I want to alert the "invalid input" syntax.

Currently my func textFieldShouldEndEditing code. How do I add code?

func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
        if Double(textField.text!) == 0 {
            let alert = UIAlertController(title: "Notice", message: "The input value can't be 0.", preferredStyle: .alert)
            let ok = UIAlertAction(title: "OK", style: .default)
            alert.addAction(ok)

            self.present(alert, animated: false)

            return false
        }
        return true
    }
Cœur
  • 37,241
  • 25
  • 195
  • 267
dinggu
  • 111
  • 7

2 Answers2

1

I get an reference from here

First add UITextFieldDelegate to your controller like this

class ViewController: UIViewController, UITextFieldDelegate 

add this in viewDidLoad

    yourTextField.delegate = self

and then

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    let isNumber = CharacterSet.decimalDigits.isSuperset(of: CharacterSet(charactersIn: string))
    let withDecimal = (
        string == NumberFormatter().decimalSeparator &&
        textField.text?.contains(string) == false
    )
    return isNumber || withDecimal
}
0

Step : 1

class ViewController: UIViewController, UITextFieldDelegate 

Step : 2 ( ViewDidLoad )

 MyTextField.delegate = self

Step : 3

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

    if string.characters.count > 0 {
        var allowedCharacters = CharacterSet.alphanumerics

        let unwantedStr = string.trimmingCharacters(in: allowedCharacters)
        return unwantedStr.characters.count == 0
    }

    return true
}

This will work for pasting strings also in to your textfield

Mick
  • 11
  • 1