Trimming whitespace from usernames and passwords

15,113

I think that it is a good practice to trim the whitespaces, since they are usually considered invalid username/password symbols (users can miss them very easily, especially if they use more than one).

NSString *trimmedString = [myString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
Share:
15,113
Andrew
Author by

Andrew

Programmer. Photographer. Father of two. Life is good.

Updated on July 26, 2022

Comments

  • Andrew
    Andrew almost 2 years

    The iPad application I'm working on requires that the user provide a username and password that are authenticated against a server before they can enter the application proper. I'm considering making a subtle change so that whitespace at the start and end of the username and password are silently ignored.

    Good idea? Bad idea? Reasons for your position?

    This has come about after I demonstrated the product to a customer today and struggled to log in. After three attempts I finally realised that I'd somehow managed to put a space before my username, and of course, that didn't match any username on the server. There's a very, very subtle difference in width with an additional space at the start of a text field on the iPad, given that the field border is spaced away from the first character anyway, and it took me some time to notice.

  • Andrew
    Andrew about 12 years
    So you advocate trimming all whitespace, not just that found at the start and end? I guess that makes sense.
  • Alexander
    Alexander about 12 years
    The function in my code sample trims (removes from beginning & end only) whitespaces, but I personally don't think spaces in usernames and passwords should be allowed.
  • Alexander
    Alexander over 8 years
    Having grown up in the last years, I should mention that my 'advice' on 'invalid' symbols is not great. Preventing people from using something just for my personal convenience is not something I advocate, especially where it concerns security-related data.
  • Dmitry Gonchar
    Dmitry Gonchar almost 8 years
    I am not so sure about password. At least you should provide error messages and prohibit saving passwords with leading/trailing spaces to make your politics clear to the user. Also read this answer stackoverflow.com/a/7240898/1343917