Search code examples
iosspecial-charactersuisearchbarnscharacterset

Prevent user entering a certain character on search bar


Is it possible to prevent the user to enter certain characters on search bar while typing. For example, the user types some string... "This is a text " and after word text the user tries enter an '*' character. I wish to prevent the user from entering that character.

Is it possible to restrict the user to enter a certain character while typing on a search bar?


Solution

  • UISearchBar has a delegate much like the one for UITextField. Implement the delegate's searchBar:shouldChangeTextInRange:replacementText: method. Return YES or NO as needed. If you return NO, the text won't be entered.

    - (BOOL)searchBar:(UISearchBar *)searchBar shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
        // check the resulting text. Return NO if not allowed
    }