How to prevent special characters in UITextField of UIAlertViewController?

434 Views Asked by At

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.

2

There are 2 best solutions below

0
Tung Vu Duc On

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
}
4
Razi Tiwana On

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
        }

    }