Skip to content

Instantly share code, notes, and snippets.

@kk-vv
Last active November 3, 2023 15:44
Show Gist options
  • Save kk-vv/1539724304e3a77c16c9a677a0363eed to your computer and use it in GitHub Desktop.
Save kk-vv/1539724304e3a77c16c9a677a0363eed to your computer and use it in GitHub Desktop.
Valid currency input
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if string.count > 0 {
if string.count == 1, textField.text.isNilOrEmpty {
if let single = string[0], (single == "." || single == "0") {// auto set . or 0 to 0.
textField.text = "0."
let newPosition = textField.endOfDocument
textField.selectedTextRange = textField.textRange(from: newPosition, to: newPosition)
textField.sendActions(for: .valueChanged)
return false
}
}
let toString = (textField.text as? NSString)?.replacingCharacters(in: range, with: string) ?? ""
if toString.count > 0 {
let regex = "(\\+)?(([0]|(0[.]\\d{0,18}))|([1-9]\\d{0,19}(([.]\\d{0,18})?)))?"
let predicate = NSPredicate(format: "SELF MATCHES %@", regex)
let matched = predicate.evaluate(with: toString)
return matched
}
} else { // delete input
if textField.text == "0" || textField.text == "0." || textField.text == "." {
textField.text = ""
textField.sendActions(for: .valueChanged)
}
return true
}
return true
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment