Remove whitespaces from the end of a textfield in swift - swift5

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)

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 }
...
}

How to add another condition in this function

How can i add another condition to my function, for another textfield and how to make this code is more simple
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
if let text = textField.text {
if let floatingLabelTextField = textField as? SkyFloatingLabelTextField {
if(text.characters.count < 3 || !text.containsString("#")) {
floatingLabelTextField.errorMessage = "Invalid email"
}
else {
// The error message will only disappear when we reset it to nil or empty string
floatingLabelTextField.errorMessage = ""
}
}
}
return true
}
Below code will be more simpler and easy to add any new condition:
func isValidEmail(testStr:String) -> Bool {
let emailRegEx = "[A-Z0-9a-z._%+-]+#[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
let emailTest = NSPredicate(format:"SELF MATCHES %#", emailRegEx)
return emailTest.evaluate(with: testStr)
}
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
guard let text = textField.text else{
return true
}
guard let floatingLabelTextField = textField as? SkyFloatingLabelTextField else {
return true
}
if isValidEmail(testStr: text) {
floatingLabelTextField.errorMessage = ""
}else{
floatingLabelTextField.errorMessage = "Invalid email"
}
return true
}
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool
{
if textField == textField as? SkyFloatingLabelTextField && (!textField.text.containsString("#") || textField.text.characters.count < 3 )
{
floatingLabelTextField.errorMessage = "Invalid email"
}
else
{
floatingLabelTextField.errorMessage = ""
}
return true
}
You can check firstly if textfield is your selected textfield and in same condition you can also check email validation.

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
}

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

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
}