yellowreign yellowreign - 2 months ago 20
Ruby Question

Rails Validate no White Space in User Name

I want to validate that a user name has no white/blank spaces for my Users. Is there a built in validation that does this? Or what is the best way to do this. Seems like it would be a pretty common requirement.

MBO MBO
Answer

I would try format validator:

validates :username, format: { with: /\A[a-zA-Z0-9]+\Z/ }

as most of the time when you don't want whitespaces in username you also don't want other characters.

Or when you really only need to check for whitespace, use without instead:

validates :username, format: { without: /\s/ }

Full documentation: http://api.rubyonrails.org/classes/ActiveModel/Validations/HelperMethods.html#method-i-validates_format_of (validates ... format: {} is the same as validates_format_of ...)