[英]Rails Models Validation 1 Word
I try to add a validation from a blog category only limited at 1 word. 我尝试从仅限于1个字的博客类别添加验证。
But I try this length: { maximum: 1 }
但我尝试这个
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: 没有Rails没有您需要的验证,但您可以轻松创建自定义验证:
Try something like this: 尝试这样的事情:
class Post < ActiveRecord::Base
validate do
if ... # any custom logic goes here
errors.add :title, "is wrong"
end
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.