Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-c How to do validation on textField

I would like to prevent the user from not entering any data as well as entering only spaces. So basically there must at least be one character without a space. Then I would also like to remove any spaces at the beginning of the word so the first letter is a character that is not a space.

edit

the user must enter something and if the user enters a few spaces before it then I want to trim those spaces. I also want to prevent the user from just entering spaces.

Example

if the user enter's a name and surname like " James Dean" I would like to take the first space away but not the second space between James and Dean.

like image 788
user1898829 Avatar asked Mar 14 '13 06:03

user1898829


2 Answers

Set your UIViewController to be your destination UITextField's delegate and implement this method:

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

  // verify the text field you wanna validate
  if (textField == _nameTextField) {

    // do not allow the first character to be space | do not allow more than one space
    if ([string isEqualToString:@" "]) {
      if (!textField.text.length)
        return NO;
      if ([[textField.text stringByReplacingCharactersInRange:range withString:string] rangeOfString:@"  "].length)
        return NO;
    }

    // allow backspace
    if ([textField.text stringByReplacingCharactersInRange:range withString:string].length < textField.text.length) {
      return YES;
    }

    // in case you need to limit the max number of characters
    if ([textField.text stringByReplacingCharactersInRange:range withString:string].length > 30) {
      return NO;
    }

    // limit the input to only the stuff in this character set, so no emoji or cirylic or any other insane characters
    NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:@"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890 "];

    if ([string rangeOfCharacterFromSet:set].location == NSNotFound) {
      return NO;
    }

  }

  return YES;
}
like image 103
Eugene Avatar answered Oct 01 '22 12:10

Eugene


try like this may be it helps to you,here is my code

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range 

    replacementString:(NSString *)string{
        if([text.text length]==0){
        if([string isEqualToString:@" "]){
            return NO;
        }
        }
        return YES;
    }

By placing this code user won't enter space as a first letter but it accepts the space in the middle of the string.

like image 23
Balu Avatar answered Oct 01 '22 10:10

Balu