Should I trim spaces in a password field

Leave the password as the user entered it.

You should never change silently a field put by a user, overall a password.


If you use the same trimming method when inputting in the db as you use when you select to test the password, the user's password will still work just fine.

There is of course a slight reduction of quality for that (very rare) user who choose to use white space in the beginning or end of her password.

Spaces inside passwords should never be a problem, tho.

In summary: I have not come across any good reason not to do a simple trim() for any input from web forms and the alike, passwords or not. The benefits, however, far outweighs the slight cost mentioned above.


It depends,

Some users copy their password from somewhere or fill in their password and copy paste it in the Confirm Password field. This sometimes gives a extra space before and after the password. A space will be encrypted as well while they didn't even realize a space was there.

While other users actually create passwords with spaces in.

It's totally up to you to decide your password policy. Just make sure it is very clear for the user what your password policy is. Either by alerting them if they used a space or alerting them using a space isn't allowed.


You can use this to alert user that password include spaces or something like that.

if (/^\s|\s$/.test(password)) {
    //alert('Hey Watchout');
}

Triming password is not a good practice.

Hope this helps.