Uday Babariya
Uday Babariya

Reputation: 1021

How to prevent special characters in UITextField of UIAlertViewController?

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.

Upvotes: 0

Views: 452

Answers (2)

Razi Tiwana
Razi Tiwana

Reputation: 1435

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
        }

    }

Upvotes: 2

Tung Vu Duc
Tung Vu Duc

Reputation: 1662

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
}

Upvotes: 0

Related Questions