在我的RoR应用程序中,我想阻止用户在表单的文本区域中重复特定的单词。我有一个允许用户输入文本以发送电子邮件的表格,我想阻止他们多次说“ var1”一词。这可能吗?
我已经尝试在模型中使用以下验证来做到这一点,但这是行不通的:
class Email < ActiveRecord::Base
belongs_to :account
has_many :recipients
has_many :contacts, through: :recipients, :dependent => :destroy
has_many :groups, through: :recipients, :dependent => :destroy
validate :singular_var1
private
def singular_var1
if message.scan(/"var1"/).length > 1
errors.add :message, 'You must not repeat the word VAR1'
end
end
end
由于您使用的是正则表达式,因此只需要删除引号即可:
...
if message.scan(/var1/).length > 1
errors.add :message, 'You must not repeat the word VAR1'
end
...
但是,请记住,您当前使用它的方式将只捕获小写的“ var1”,而不捕获大小写混合的字母或大写字母。如果您希望它捕获任何套管变化,请执行以下操作:
...
if message.downcase.scan(/var1/).length > 1
errors.add :message, 'You must not repeat the word VAR1'
end
...
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句