0

In my app I have a textfield in which users have to enter a string from 1-25 characters. The problem I'm having is stopping them from only entering spaces. I want them to be able to use spaces but only if they have other characters (abc, 1-9, etc.). How can I stop them from only entering spaces?

Matt Sarabyte
  • 245
  • 1
  • 3
  • 10
  • 2
    possible duplicate of [How to know if a UITextField in iOS has blank spaces](http://stackoverflow.com/questions/8238691/how-to-know-if-a-uitextfield-in-ios-has-blank-spaces) – jprofitt Feb 04 '14 at 04:30

3 Answers3

2

In your view controller set delegate of UITextField to self. Then implement following method.

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range
replacementString:(NSString *)string {

  if([[textField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length] == 0){
      return NO;
   }

  return YES;
}
Akshay Nalawade
  • 1,447
  • 2
  • 14
  • 29
1

Sounds like this question might help.

Just trim the whitespace off the string and then check to see if it is the empty string.

Community
  • 1
  • 1
therealrootuser
  • 10,215
  • 7
  • 31
  • 46
0

Perform a whitespace "trim" on their input and check to see if the result matches an empty string.

Nick Coad
  • 3,623
  • 4
  • 30
  • 63