Always strip whitespace when searching exact match user input

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the user-input-and-output category.

Last Updated: 2021-05-16

I had the following code for resetting passwords for a particular email address, yet people sometimes complained about not receiving reset emails. (There was no delivery issue)

email = user_params[:email].downcase
user = User.find_by(email: email)
flash[:notice] =
  'Reset password request received. For privacy reasons we cannot reveal whether ' \
  "#{user_params[:email]} is on file with us. If you receive no email within 5 minutes, try " \
  'a different address.'

The issue was that users added whitespace before and after their email sometimes — I fixed as follows

email = user_params[:email].downcase.strip


When matching exactly against user input in the DB, be sure to trim whitespace. The best place is probably at the middleware level so it's global.