Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save shekarsiri/2822b0958e967860ed07d2d63529ffeb to your computer and use it in GitHub Desktop.
Save shekarsiri/2822b0958e967860ed07d2d63529ffeb to your computer and use it in GitHub Desktop.
UITextField accept only numbers to certain limits (Swift 3 Tested.)
// let MAX_LENGTH_PHONENUMBER = 15
// let ACCEPTABLE_NUMBERS = "0123456789"
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let newLength: Int = textField.text!.characters.count + string.characters.count - range.length
let numberOnly = NSCharacterSet.init(charactersIn: ACCEPTABLE_NUMBERS).inverted
let strValid = string.rangeOfCharacter(from: numberOnly) == nil
return (strValid && (newLength <= MAX_LENGTH_PHONENUMBER))
}
@kuratowsky
Copy link

Hello dear friend,
Thanks for your gist! It's make my day!!
Here my fork tested in Swift 5,
https://gist.github.com/kuratowsky/6e027fd2270d5bf5ac4ee41764e4bfdb

Regards

@aishwaryagiram4
Copy link

Thank You

Copy link

ghost commented Jun 10, 2020

tnx

@Ka4aH4uk
Copy link

Thank u

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment