2

I try to add a validation from a blog category only limited at 1 word.

But I try this length: { maximum: 1 }

I doesn't work. Is there a validation to validaes only one word and not uniqueness?

Thank you for your answers

Hussein.
  • 179
  • 2
  • 11

3 Answers3

8

You can make a custom validation:

validates :category, uniqueness: true
validate :category_in_1_word

private

def category_in_1_word
  if category.to_s.squish.split.size != 1
    errors.add(:category, 'must be 1 word')
  end
end
Hieu Pham
  • 6,577
  • 2
  • 30
  • 50
5

you can try:

validates :category, :format => { :with => /^[A-Za-z]+$/, :message => "Must be single word" }
Pitabas Prathal
  • 1,006
  • 1
  • 12
  • 15
0

No Rails doesn't have the validation you need, but you can easily create a custom one:

Try something like this:

class Post < ActiveRecord::Base
  validate do
    if ... # any custom logic goes here
      errors.add :title, "is wrong"
    end
  end
end
Dmitry Sokurenko
  • 6,042
  • 4
  • 32
  • 53