I need to implement a validation in TextField that will stop the user to enter anything besides the allowed requirements.
The validations must contain:
- Allow only numbers and decimal points
.
- The highest allowed number should be 9999999999
- Stop users from writing two
.
in the TextField - Allow a maximum of two decimal numbers after the point (1, 1.9, and 1.99 are acceptable, 1.999 is not acceptable).
- It should be aware that if the user tries to paste some text or any number that doesn't pass the requirements, it should not allow that.
I tried an implementation, but sometimes is not working. I don't understand how is that affected.
var dotLocation = Int()
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if string == "," {
textField.text = textField.text! + "."
return false
}
let nonNumberSet = CharacterSet(charactersIn: "0123456789.").inverted
let allowedCharacters = CharacterSet(charactersIn:"0123456789.")//Here change this characters based on your requirement
let characterSet = CharacterSet(charactersIn: string)
if Int(range.length) == 0 && string.count == 0 {
return true
}
if (string == ".") {
if Int(range.location) == 0 {
return false
}
if dotLocation == 0 {
dotLocation = range.location
return true
} else {
return false
}
}
if range.location == dotLocation && string.count == 0 {
dotLocation = 0
}
if dotLocation > 0 && range.location > dotLocation + 2 {
return false
}
if range.location >= 10 {
if dotLocation >= 10 || string.count == 0 {
return true
} else if range.location > dotLocation + 2 {
return false
}
var newValue = (textField.text as NSString?)?.replacingCharacters(in: range, with: string)
newValue = newValue?.components(separatedBy: nonNumberSet).joined(separator: "")
textField.text = newValue
return allowedCharacters.isSuperset(of: characterSet)
} else {
return allowedCharacters.isSuperset(of: characterSet)
}
return true
}
What would be the best implementation in such a case? Thanks for your contribution.