Reputation: 1651
I want to achieve following:
I am using decimal keypad. Below code handles first and third item above:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let currentString: NSString = (textField.text ?? "") as NSString
let newString = currentString.replacingCharacters(in: range, with: string)
return newString.count <= 10
}
Thank you for your time.
Upvotes: 3
Views: 5056
Reputation: 749
Bellow code will check all conditions you have specified
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
//Prevent "0" characters as the first characters. (i.e.: There should not be values like "003" "01" "000012" etc.)
if textField.text?.count == 0 && string == "0" {
return false
}
//Limit the character count to 10.
if ((textField.text!) + string).count > 10 {
return false
}
//Have a decimal keypad. Which means user will be able to enter Double values. (Needless to say "." will be limited one)
if (textField.text?.contains("."))! && string == "." {
return false
}
//Only allow numbers. No Copy-Paste text values.
let allowedCharacterSet = CharacterSet.init(charactersIn: "0123456789.")
let textCharacterSet = CharacterSet.init(charactersIn: textField.text! + string)
if !allowedCharacterSet.isSuperset(of: textCharacterSet) {
return false
}
return true
}
Upvotes: 10
Reputation: 175
You can Create this method to prevent from copy paste
override func canPerformAction(action: Selector, withSender sender: AnyObject?) -> Bool {
if action == "paste:" {
return false
}
return super.canPerformAction(action, withSender: sender)
}
and also you can add the following code to shouldChangeCharactersInRange
Delegate method of textfield
let searchString = (txtMobilePhone.text as NSString?)?.replacingCharacters(in: range, with: string)
if (searchString?.length)! > 1 {
let inverseSet = CharacterSet(charactersIn: ".0123456789").inverted
return ((string as NSString).rangeOfCharacter(from: inverseSet).location == NSNotFound)
} else {
let inverseSet = CharacterSet(charactersIn: ".123456789").inverted
return ((string as NSString).rangeOfCharacter(from: inverseSet).location == NSNotFound)
}
this above will only allow the user to enter the "0" after the second character I mean restricts the user to type "0" at the starting of numbers
Upvotes: 0
Reputation: 15784
You can use regex that define a number with <= 10 digits and not starting with 0, then use NSPredicate or NSRegularExpression to validate the entered text. Something like this:
func isAllowed(str: String?) -> Bool {
let regexPattern: String = "^((?!(0))[0-9]{0,10})$"
let predicate = NSPredicate(format:"SELF MATCHES %@", regexPattern)
return predicate.evaluate(with: str)
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
return isAllowed(str: textField.text)
}
Upvotes: 1