I have a Review Model in Rails which has a rating and a comment. Right now I validate rating, presence true and I don't validate a comment on presence in case users don't want to type a comment. I would like to be able to validate a comment if it's empty. However, if the user decides to type a comment, I would like to validate with length of minimum 10 words.
I found in Rails Guide how to validate length for min or maximum characters. But I have not found how to make a condition:
If it's empty it's ok, If it's not empty, have at least 10 words.
Any help would be greatly appreciated.
validates :comment, length: { minimum: 10 }, :allow_blank => true
I like Ninjarabbi's answer, but it's counting characters, not words.
You can use a custom validation method.
validate :comment_has_enough_words
def comment_has_enough_words
return if comment.blank?
errors.add(:comment, "must be at least 10 words") if comment.split.size < 10
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.