Search code examples
iosswiftuitextfielduitextfielddelegate

How to allow numbers and letters only without any whitespace and exactly 8 characters in UITextField


I am a new bee to swift iOS development and I require to allow only numbers and alphabets without any whitespace and exactly 8 characters to be entered into the UITextField.

For only numbers and alphabets without any white space I follow the logic:

extension [YourViewController]: UITextFieldDelegate
{
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
            do {
                let regex = try NSRegularExpression(pattern: ".*[^A-Za-z0-9 ].*", options: [])
                if regex.firstMatch(in: string, options: [], range: NSMakeRange(0, string.count)) != nil {
                    return false
                }
            }
            catch {
                print("ERROR")
            }
        return true
}
}

              

I want to include the logic of exactly 8 characters along with this . How to achieve this!?


Solution

  • Try this code, it might help you achieve your goal:

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        do {
            let text = (textField.text! as NSString).replacingCharacters(in: range, with: string)
            let regex = try NSRegularExpression(pattern: "^([a-zA-Z0-9]{0,10})$", options: [])
            if regex.firstMatch(in: text, options: [], range: NSMakeRange(0, text.count)) != nil {
                return true
            }
        }
        catch {
            print("ERROR")
        }
        return false
    }