(作为此问题的后续内容: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标签,然后检查字符长度..
答案 0 :(得分:4)
我认为您可以在验证中使用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