Last active
November 3, 2023 15:44
-
-
Save kk-vv/1539724304e3a77c16c9a677a0363eed to your computer and use it in GitHub Desktop.
Valid currency input
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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