Call function from text field delegate method and get valid username.
let USERNAMERANGE = "ABCDEFGHIJKLMONPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_." let KALERTVALIDUSERNAME = "Username can only use letters, numbers, underscore and periods." public func setUsernameFormate(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String)-> Bool{ var strUserName = textField.text! as String if string == " " { strUserName = strUserName + "_" return false } let currentCharacterCount = textField.text?.characters.count ?? 0 if (range.length + range.location > currentCharacterCount){ return false } let newLength = currentCharacterCount + string.characters.count - range.length if newLength <= 20 { let set = NSCharacterSet(charactersIn: USERNAMERANGE).inverted if string.rangeOfCharacter(from: set) != nil{ topAlertActionError(msgAlert: KALERTVALIDUSERNAME) } return string.rangeOfCharacter(from: set) == nil } else{ return false } }