Swift 3 - Limit TextField to alphanumeric (with whitespace and hypens) - swift

Want to limit Textfield input to only A-Z,a-z,0-9, " " and -. Currently have:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool
{
if self.isNumericTextInput{
let allowedCharacters = CharacterSet.decimalDigits
let characterSet = CharacterSet(charactersIn: string)
if allowedCharacters.isSuperset(of: characterSet) && returnFlag{
return true
} else{
return false
}
} else{
// Allow only alphanumerics, whitespace and hyphens
}
return
}

Though it's late to answer, but it might be useful to someone.
Swift 3:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
/// 1. replacementString is NOT empty means we are entering text or pasting text: perform the logic
/// 2. replacementString is empty means we are deleting text: return true
if string.characters.count > 0 {
var allowedCharacters = CharacterSet.alphanumerics
allowedCharacters.insert(charactersIn: " -") // "white space & hyphen"
let unwantedStr = string.trimmingCharacters(in: allowedCharacters)
return unwantedStr.characters.count == 0
}
return true
}
Note: This will work for pasting strings into the text field as well. Pasted string will not be displayed in text field if it contains any unwanted characters.

Try this:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let characterSet = CharacterSet(charactersIn: string)
let allowedCharacters = (self.isNumericTextInput
? CharacterSet.decimalDigits
: CharacterSet(charactersIn: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 -"))
return allowedCharacters.isSuperset(of: characterSet) && returnFlag
}

Related

specify a maximum Value for a UITextField in Swift

I need to specify a maximum value for a text field. I already got an answer from another post on how to restrict a UITextField to numbers only. But I would like to modify that function to only accept a number between 0 and 540.
Is there any way to modify that function?
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let s = NSString(string: textField.text ?? "").replacingCharacters(in: range, with: string)
guard !s.isEmpty else { return true }
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .none
return numberFormatter.number(from: s)?.intValue != nil
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
print(string)
let myRange = 0...540
//ro delete/remove values in textField
if string == "" {
return true
}
let fullText = NSString(string: textField.text ?? "").replacingCharacters(in: range, with: string)
if let wholeNumber = Int(fullText), myRange.contains(wholeNumber) {
return true
}
return false
}
You can check if number lies between 0 and 540.
if let number = numberFormatter.number(from: s)?.intValue {
return number > 0 && number < 540
} else {
return true
}

Set max length UITextField

How to limit the number of characters in a UITextField?
I need to to display max 10 characters
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let textFieldCadena = textField.text, let range = Range(range, in: textFieldCadena) else {
return false
}
let nuevaCadena = textFieldCadena.replacingCharacters(in: range, with: string)
if nuevaCadena.isEmpty {
textField.text = "0"
return false
} else if textField.text == "0" {
textField.text = string
return false
}
if textField == textField {
let allowedCharacters = CharacterSet(charactersIn:"0123456789 ")
let characterSet = CharacterSet(charactersIn: string)
return allowedCharacters.isSuperset(of: characterSet)
}
return true
}
As decribed here You can use .maxlength in swift 5 to set character length. Credit to article here:
https://www.swiftdevcenter.com/max-character-limit-of-uitextfield-and-allowed-characters-swift/
self.textField.maxLength = 10
Do the check for character count first
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard
let textFieldCadena = textField.text,
let range = Range(range, in: textFieldCadena),
textFieldCadena.count <= 10
else { return false }
...
}

Remove whitespaces from the end of a textfield in swift

I have an email textfield which comes while registration of the user. If I add a space at the end of the email I am unable to register the user.
How can I remove the space at the end?
Eg: abc#gmail.com+space this space should be removed.
Do like this:
email.text! = email.text!.replacingOccurencesOf(" ", withString: "")
or:
let string = textField.text?.trimmingCharacters(in: .whitespaces)
or:
func textField(textField: UITextField!, shouldChangeCharactersInRange range: NSRange, replacementString string: String!) -> Bool {
if range.location == 0 && string == " " {
return false
}
return true
}
let verifiedEmailString = emailString.replacingOccurencesOf(of:" ", with: "")
UPDATE:
Implement UITextFields Delegate method like this:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let cs = Character(" ")
let filtered = string.components(separatedBy: cs).joined(separator: "")
return (string == filtered)
}
Use this common method in your helper class:
Description:
func trimWhiteSpace(str: String) -> String {
let trimmedString = str.trimmingCharacters(in: NSCharacterSet.whitespaces)
return trimmedString
}
Usage:
let string = trimWhiteSpaceNew(str: textfield.text)

put character count and character type limit for the textfield swift 4

I would like to put a limit for textfield. Example: Max character count should be 6 and characters can be digits only. But i could not put these two controls in one function.
First func for count of the text:
func textFieldCharacterCountLimit(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let maxLength = 6
let currentString: NSString = txt_phone_no_verification_code.text! as NSString
let newString: NSString =
currentString.replacingCharacters(in: range, with: string) as NSString
return newString.length <= maxLength
}
Second func for type of the text:
func textFieldCharacterTypeLimit(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let allowedCharacters = CharacterSet.decimalDigits
let characterSet = CharacterSet(charactersIn: string)
return allowedCharacters.isSuperset(of: characterSet)
}
Beside this, it gives an error also. And textFieldCharacterCountLimit function does not work. I think i get an error because two functions effect same textfield with return. Thanks
Allowing only a specified set of characters to be entered into a given text field with specific range
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if string.count == 0 {
return true
}
let currentText = textField.text ?? ""
let prospectiveText = (currentText as NSString).replacingCharacters(in: range, with: string)
return prospectiveText.containsOnlyCharactersIn(matchCharacters: "0123456789") &&
prospectiveText.count <= 6
}
String extension with condition
extension String {
// Returns true if the string contains only characters found in matchCharacters.
func containsOnlyCharactersIn(matchCharacters: String) -> Bool {
let disallowedCharacterSet = NSCharacterSet(charactersIn: matchCharacters).inverted
return self.rangeOfCharacter(from: disallowedCharacterSet as CharacterSet) == nil
}
}
How to program an iOS text field that takes only numeric input with a maximum length
http://www.globalnerdy.com/2015/04/27/how-to-program-an-ios-text-field-that-takes-only-numeric-input-or-specific-characters-with-a-maximum-length/
You can't just make up delegate method names. You need to implement the proper method and do all of your needed checking in the one method.
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let newString = (textField.text! as NSString).replacingCharacters(in: range, with: string)
if newString.count > 6 {
return false
}
return newString.rangeOfCharacter(from: CharacterSet.decimalDigits.inverted) == nil
}

Value of tuple Void (aka ()) has no member "isSuperset"

I created a union between two character sets to be able to use a period with the decimalDigits character set.
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let allowed = CharacterSet.decimalDigits
let period = CharacterSet.init(charactersIn: ".")
let both = CFCharacterSetUnion(allowed as! CFMutableCharacterSet, period as CFCharacterSet)
let characterSet = NSCharacterSet(charactersIn: string)
return both.isSuperset(of: characterSet as CharacterSet)
}
however, returning "both.isSuperset(of: characterSet as CharacterSet)". how to correct?
Update 1:
Errors displayed with the current suggested answer
Update 2:
latest update
Try doing this instead:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
var allowed = CharacterSet.decimalDigits
let period = CharacterSet.init(charactersIn: ".")
allowed.formUnion(period)
//UNCOMMENT when isSuperset is working
//let characterSet = CharacterSet(charactersIn: string)
//return allowed.isSuperset(of: characterSet)
// Swift 3 appropriate solution
let isSuperset = string.rangeOfCharacter(from: allowed.inverted) == nil
return isSuperset
}
the basis for which I found here.
Even better, make "allowed" (or "both", whatever you decide to name it) a property that gets created in viewDidLoad so you don't recreate and union the character sets each time a character is typed.