I am trying to add some validation to amount in textField.I am trying to allow user to add valid numbers using Decimal Keypad. User can add numbers less than 100000 (99999.99,9999,9,1) User cant add numbers like [12.. , 12.0.2 , 12.345 , 100.23456
Here is what i tried. if i try to add max length to 5.i could not be able to add 99999.99. If i add max length to 8. i can able to add numbers more than 99999. Hope u understand my problem.Thanks in advance
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let maxLength = 5
var newString : NSString = ""
if(textField.tag == 3){
let currentString: NSString = tvAmount.text! as NSString
newString =
currentString.replacingCharacters(in: range, with: string) as NSString
// max 2 fractional digits allowed
let newText = (textField.text! as NSString).replacingCharacters(in: range, with: string)
let regex = try! NSRegularExpression(pattern: "\\..{3,}", options: [])
let matches = regex.matches(in: newText, options:[], range:NSMakeRange(0, newText.characters.count))
guard matches.count == 0 else { return false }
if(newString.length < 5){
switch string {
case "0","1","2","3","4","5","6","7","8","9":
return true
case ".":
let array = textField.text?.characters.map { String($0) }
var decimalCount = 0
for character in array! {
if character == "." {
decimalCount = decimalCount + 1
}
}
if decimalCount == 1 {
return false
} else {
return true
}
default:
let array = string.characters.map { String($0) }
if array.count == 0 {
return true
}
return false
}
}
else{
}
}
return newString.length <= maxLength
}