Doug Steinberg
Doug Steinberg

Reputation: 1162

rails validation for one word

I need to create a validation for field to ensure that it is only one word.

Here is what I have, but it only validates that the length is 1 character , not one word

validates_length_of :name, maximum: 1, too_many_words: 'Please choose a name with only one word', tokenizer: ->(str) { str.scan(/\w+/) }

I found the example I'm working with here http://www.rubydoc.info/docs/rails/4.1.7/ActiveModel/Validations/HelperMethods:validates_length_of

Upvotes: 0

Views: 1109

Answers (2)

Serhiy Nazarov
Serhiy Nazarov

Reputation: 379

validates :name,
              :presence => true,
              :uniqueness => true,
              :length => {
                  :maximum => 1,
                  :tokenizer => lambda {|str| str.scan(/\w+/)},
                  :too_long => "Name must be one word."
              }

Upvotes: 2

Doug Steinberg
Doug Steinberg

Reputation: 1162

I actually found the answer here http://guides.rubyonrails.org/active_record_validations.html

validates :name, length: {
    maximum: 1,
    tokenizer: lambda { |str| str.split(/\s+/) },
    too_long: "Please choose a name that is only %{count} word."
  }

Upvotes: 2

Related Questions