Search code examples
swiftfirebaseuser-inputsignnon-english

can i force the user input in login or signup screen to be only in english


i'm traying to force the user input to be only in English so if the user sign up prevent the user from sign up with other language I don't know if firebase have already prevent the users from that behind the seen but if they didn't do that, is there any programmatic way in code , or this is not a really a problem in developing app and i'm just freaking out

func textField(_ textFieldToChange: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    if textFieldToChange == username {
        let characterSetNotAllowed = CharacterSet.whitespaces
        if let _ = string.rangeOfCharacter(from:NSCharacterSet.uppercaseLetters) {
            return false
        }
        if let _ = string.rangeOfCharacter(from: characterSetNotAllowed, options: .caseInsensitive) {
            return false
        } else {
            return true
        }
    }
    return true
}

Solution

  • You can start subclassing UITextField and add a target for editing changed UIControlEvents and filter your the string entered by the user when it changes:

    class EnglishLettersField: UITextField {
        override func willMove(toSuperview newSuperview: UIView?) {
            addTarget(self, action: #selector(editingChanged), for: .editingChanged)
            editingChanged(self)
        }
        @objc func editingChanged(_ textField: UITextField) {
            guard let text = textField.text?.englishLetters else { return }
            textField.text = text
        }
    }
    extension CharacterSet {
        // create your own set with the allowed characters to filter your string
        static let englishLetters = CharacterSet(charactersIn: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ")
    }
    
    extension String {
        // create a computed property to separate the original text using the custom character set inverted, join it again and return it
        var englishLetters: String {
            return components(separatedBy: CharacterSet.englishLetters.inverted).joined()
        }
    }
    

    You can add it programatically to your view or using the interface builder

    class ViewController: UIViewController {
        override func viewDidLoad() {
            super.viewDidLoad()
            let englishLettersField = EnglishLettersField(frame: CGRect(origin: CGPoint(x: 50, y: 50), size: CGSize(width: 200, height: 50)))
            view.addSubview(englishLettersField)
        }
    }
    

    sample project