yellowreign
yellowreign

Reputation: 3638

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.

Upvotes: 21

Views: 17823

Answers (5)

Aniket Tiwari
Aniket Tiwari

Reputation: 3998

You can use before_validation callback to strip whitespace

class User
  before_validation :strip_blanks

  protected

  def strip_blanks
    self.username = self.username.strip
  end
end

Upvotes: 1

Zach S
Zach S

Reputation: 77

In your User model add validation. validates :username, format: { without: /\s/ } will remove white/blank spaces for your Users. You can even add a message alerting the user that their username contains whitespace.

class User < ActiveRecord::Base

 validates :username, format: { without: /\s/, message: "must contain no spaces" }

end

Upvotes: 2

MBO
MBO

Reputation: 30995

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 ...)

Upvotes: 65

dax
dax

Reputation: 10997

MurifoX's answer is better, but regarding it being a common requirement, i think this is more often used:

validates :presence

class User < ActiveRecord::Base
  validates :name, presence: true
end

Upvotes: -1

MurifoX
MurifoX

Reputation: 15089

I believe you will have to create a custom validator:

validate :check_empty_space

def check_empty_space
  if self.attribute.match(/\s+/)
    errors.add(:attribute, "No empty spaces please :(")
  end
end

Upvotes: 6

Related Questions