0

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.

User
  • 169
  • 1
  • 11
  • Try to use `errors.add(:promo_code, "No empty spaces please :(")` instead of :attribute – Toni Jan 19 '22 at 09:38
  • @Toni It is still not working. – User Jan 19 '22 at 11:33
  • What does this return if you debug the validation: `self.promo_code.match(/\s+/)`. If object is return, you have space in the string. You can also try with `self.promo_code =~ /\s/`, which should return the index of first space found. So if that condition returns any number, string has spaces, if returns "nil", string has no spaces. – Toni Jan 19 '22 at 13:39

1 Answers1

1

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.

Hackman
  • 1,614
  • 1
  • 12
  • 15
  • The rails version that I am using is 4.2.11.3 – User Jan 19 '22 at 12:55
  • Looks like that version should work the same way. Can you tell me how did you try it? Did you create a new record without putting anything into the input or did you add text with a space? – Hackman Jan 19 '22 at 13:03
  • This input field is compulsory so I have added the text with a space and it is still allowing the whitespaces. – User Jan 19 '22 at 13:43
  • If you go into your rails console and you build a new record with spaces inside the promo_code without saving it and call `.valid?` on it, does it returns true or false? – Hackman Jan 19 '22 at 13:47
  • It is returning false. – User Jan 19 '22 at 13:52
  • That means your validation is working and you skip validations when you create it with your form. Can you show the piece of code from the controller where you are saving it? – Hackman Jan 19 '22 at 13:58
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/241210/discussion-between-hackman-and-user). – Hackman Jan 19 '22 at 14:07