Add UITextField in your controller or view

class UITextViewController: UIViewController{
@IBOutlet weak var mtnGSMtxt: UITextField!
override func viewDidLoad() {
mtnGSMtxt.delegate = self
super.viewDidLoad()
}
}

Now extend defined class with UITextFieldDelegate:

extension UITextViewController : UITextFieldDelegate{
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
//For GSM numer validation
let maxLength = 12    
if textField == mtnGSMtxt {
        let gsmLength = Int(mtnGSMtxt.text?.count ?? 0)
        if gsmLength >= 0 && gsmLength < maxLength{
            let allowedCharacters = CharacterSet(charactersIn:"0123456789 ")//Here change this characters based on your requirement
            let characterSet = CharacterSet(charactersIn: string)
            return allowedCharacters.isSuperset(of: characterSet)
        }else{
            return false
        }

    }
    return true
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *