(作为此问题的后续:In Jquery AND Rails, how to get visible character count of a string?)
假设您有一个带有嵌入链接和标签的字符串,如下所示:
This string has <a href="http://www.google.com">some links</a> inside it.
那么用户可见的字符串是:
This string has some links inside it.
完整字符串有 73 个字符,可见字符串只有 37 个字符。
假设我现在想编写一个 Rails 验证(自定义验证)来检查字符串的可见长度。即:
validate :string_visible_length
def string_visible_length
#some code that verifies the character length of a field named :field_name
end
有什么想法可以实现这一点吗?我需要去掉 html 标签,然后检查字符长度..
最佳答案
我认为你可以使用 strip links验证中的方法。
使助手在模型文件中可用:
include ActionView::Helpers
这是验证:
validate :string_visible_length
private
def string_visible_length
visible_string = strip_links(self.column_name) # where column_name is the field you need validated
errors.add(:base, 'Visible string is too long') if visible_string.length > 20 # 20 is whatever length you need
end
关于ruby-on-rails - 如何在 Ruby on Rails 中编写可见字符计数验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7364269/