Mantosh Kumar
Mantosh Kumar

Reputation: 273

Prevent special characters in UITextField

How can I prevent the user from entering special characters in UITextField?

Upvotes: 4

Views: 10923

Answers (5)

Markymark
Markymark

Reputation: 2979

Here's an example of how you can allow users to only type alphanumeric characters using RxSwift.

Add the RxSwift pod

pod 'RxSwift', '~> 5'

Create a String extension to remove characters in a set

extension String {

    func removeChars(in set: CharacterSet) -> String {
        let filtered = self.unicodeScalars.filter { (scalarElement) -> Bool in
            if (set.contains(scalarElement)) {
                return false
            }

            return true
        }
        
        let trimmed = String(filtered.map({ (scalar) -> Character in
            return Character(scalar)
        }))
        
        return trimmed
    }

}

Use the RxSwift extension to remove invalid chars when the text changes

import UIKit
import RxSwift


class MyViewController: UIViewController {
    
    private let disposeBag = DisposeBag()


    override func viewDidLoad() {
        super.viewDidLoad()
        
        setUpView()
    }

    private func setUpView() {
        //Do view set up stuff here

        //Use the extension here to listen to text changes and remove chars
        myTextField.rx.text
            .asDriver(onErrorJustReturn: "")
            .drive(onNext: { [weak self] (text: String?) in
                //Here you would change the character set to what you need
                let newText = text?.removeChars(in: CharacterSet.alphanumerics.inverted)
                self?.myTextField.text = newText
            })
            .disposed(by: disposeBag)
    }

}

Upvotes: -1

PK Chahar
PK Chahar

Reputation: 111

try with this

self.DataTblView.scrollToRow(at: IndexPath(row: 0, section: 0), at: .top, animated: false)

Upvotes: -2

McDonal_11
McDonal_11

Reputation: 4075

One more answer with default CharacterSet

Restrict all Special characters and also, this will support if any string you dont want to restrict.

extension String {
    var containsValidCharacter: Bool {
        guard self != "" else { return true }
        let noNeedToRestrict = CharacterSet(charactersIn: " _") // NOT RESTRICT "Underscore and Space"
        if noNeedToRestrict.containsUnicodeScalars(of: self.last!) {
            return true
        } else {
            return CharacterSet.alphanumerics.containsUnicodeScalars(of: self.last!)
        }
    }
}
extension CharacterSet {
    func containsUnicodeScalars(of character: Character) -> Bool {
        return character.unicodeScalars.allSatisfy(contains(_:))
    }
}

Usage:

extension ViewController: UITextFieldDelegate {

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        return string.containsValidCharacter
    }
}

Upvotes: 1

Ahmed Safadi
Ahmed Safadi

Reputation: 4590

Swift 4.2

for emoji and special character

override func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if textField.isFirstResponder {
            let validString = CharacterSet(charactersIn: " !@#$%^&*()_+{}[]|\"<>,.~`/:;?-=\\¥'£•¢")

            if (textField.textInputMode?.primaryLanguage == "emoji") || textField.textInputMode?.primaryLanguage == nil {
                return false
            }
            if let range = string.rangeOfCharacter(from: validString)
            {
                print(range)
                return false
            }
        }
        return true
    }

Upvotes: 2

Mantosh Kumar
Mantosh Kumar

Reputation: 273

I solved the problem using this code:

let validString = NSCharacterSet(charactersInString: " !@#$%^&*()_+{}[]|\"<>,.~`/:;?-=\\¥'£•¢")

// restrict special char in test field
if (textField == self.txt_firstName || textField == self.txt_lastName)
{
    if let range = string.rangeOfCharacterFromSet(validString)
    {
        print(range)
        return false
    }
    else
    {
    }
}

Upvotes: 6

Related Questions