0

I have UIAlertViewController as shown below image.
enter image description here

here's my code :

let alertController = UIAlertController(title: alertTitle.security, message: "", preferredStyle: UIAlertController.Style.alert)
    alertController.addTextField { (textField : UITextField!) -> Void in
        textField.placeholder = placeholder.security
        textField.tintColor = .black
        textField.isSecureTextEntry = true
    }

I want to prevent some special characters to insert into UITextField.

Uday Babariya
  • 1,031
  • 1
  • 13
  • 31
  • Answer : https://codereview.stackexchange.com/questions/187441/prevent-a-uitextfield-from-being-input-with-aphabetic-characters – dahiya_boy Apr 17 '19 at 10:23

2 Answers2

2

You Have to assign the textfield the delegate

textField.delegate = self 

then check check if special character or not

 extension ViewController: UITextFieldDelegate {
        public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
            if textField.isFirstResponder {
                let validString = CharacterSet(charactersIn: "!@#$%^&*()_+{}[]|\"<>,.~`/:;?-=\\¥'£•¢")


                if let range = string.rangeOfCharacter(from: validString) {
                    return false
                }
            }
            return true
        }

    }
Razi Tiwana
  • 1,425
  • 2
  • 13
  • 16
0

Hope this help :

let alertController = UIAlertController(title: alertTitle.security, message: "", preferredStyle: UIAlertController.Style.alert)
    alertController.addTextField { (textField : UITextField!) -> Void in
        textField.placeholder = placeholder.security
        textField.tintColor = .black
        textField.isSecureTextEntry = true
        textField.delegate = self // new
    }


func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    if string == "(special chracter)" {
        return false
    }
    return true
}
Tung Vu Duc
  • 1,552
  • 1
  • 13
  • 22