简体   繁体   中英

Rails Models Validation 1 Word

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

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

你可以试试:

validates :category, :format => { :with => /^[A-Za-z]+$/, :message => "Must be single word" }

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM