I am currently checking my UITextField
, which is set to show Numeric Keypad in shouldChangeCharactersIn
to limit the input to only one decimal separator and only 2 decimal points like this (thanks to this question):
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let decimalSeparator = String(Locale.current.decimalSeparator ?? ".")
if (textField.text?.contains(decimalSeparator))! {
let limitDecimalPlace = 2
let decimalPlace = textField.text?.components(separatedBy: decimalSeparator).last
if (decimalPlace?.count)! < limitDecimalPlace {
return true
} else {
return false
}
}
}
This works great. However, it is now possible to insert whatever value the user wants, which I want to limit to a value lower than 999. I used to check the length to allow only 3 characters, but now I want to allow following values (for example):
143
542.25
283.02
19.22
847.25
But I don't want to allow:
2222
3841.11
999.99
How could I do that?