Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know if a UITextField in iOS has blank spaces

I have a UITextField where user can enter a name and save it. But, user should not be allowed to enter blank spaces in the textFiled.

1 - How can I find out,if user has entered two blank spaces or complete blank spaces in the textFiled

2 - How can i know if the textFiled is filled only with blank spaces

edit - It is invalid to enter only white spaces(blank spaces)

like image 625
A for Alpha Avatar asked Nov 23 '11 07:11

A for Alpha


People also ask

How check TextField is empty or not in Swift?

storyboard add one textField, one button and one label one below other as shown in the figure. On click of the button we will check whether the text field is empty or not and show the result in label. @IBOutlet weak var textField: UITextField! @IBOutlet weak var resultLabel: UILabel!

What is UITextField in xcode?

An object that displays an editable text area in your interface.

What is TextField in swift?

A TextField is a type of control that shows an editable text interface. In SwiftUI, a TextField typically requires a placeholder text which acts similar to a hint, and a State variable that will accept the input from the user (which is usually a Text value).


1 Answers

You can "trim" the text, that is remove all the whitespace at the start and end. If all that's left is an empty string, then only whitespace (or nothing) was entered.

NSString *rawString = [textField text]; NSCharacterSet *whitespace = [NSCharacterSet whitespaceAndNewlineCharacterSet]; NSString *trimmed = [rawString stringByTrimmingCharactersInSet:whitespace]; if ([trimmed length] == 0) {     // Text was empty or only whitespace. } 

If you want to check whether there is any whitespace (anywhere in the text), you can do it like this:

NSRange range = [rawString rangeOfCharacterFromSet:whitespace]; if (range.location != NSNotFound) {     // There is whitespace. } 

If you want to prevent the user from entering whitespace at all, see @Hanon's solution.

like image 165
DarkDust Avatar answered Oct 14 '22 01:10

DarkDust