User
User

Reputation: 209

How to restrict white/blank spaces in an input field in rails model?

I want to put restriction on a field so that user cannot enter white/blank space. I have tried multiple solutions but nothing works.

Following are some solutions that I have tried -

validates :promo_code, format: { with: /\A[a-zA-Z0-9]+\Z/ }
normalize_attribute :promo_code, :with => :strip
validate :check_empty_space

def check_empty_space
  if self.promo_code.match(/\s+/)
    errors.add(:attribute, "No empty spaces please :(")
  end
end
 validates :promo_code, format: { without: /\s/, message: "must contain no spaces" }

Rails before_validation strip whitespace best practices

Please suggest something that actually works.

Upvotes: 0

Views: 1100

Answers (1)

Hackman
Hackman

Reputation: 1729

I got the following validation working to prevent having whitespaces:

validates :promo_code, format: { without: /\s/, message: 'No empty spaces please :(' }

If that's not working for you, then please add the version of rails you are using.

Upvotes: 1

Related Questions