【问题标题】:Ruby on Rails: Validate the number of times a user enters a word on a formRuby on Rails:验证用户在表单上输入单词的次数
【发布时间】:2017-02-09 21:35:14
【问题描述】:

在我的 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

【问题讨论】:

    标签: ruby-on-rails regex validation


    【解决方案1】:

    由于您使用的是正则表达式,您只需删除引号:

    ...
    
    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
    
    ...
    

    【讨论】:

      猜你喜欢
      • 2019-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-12
      • 1970-01-01
      相关资源
      最近更新 更多