jeudi 9 février 2017

Ruby on Rails: Validate the number of times a user enters a word on a form

In my RoR application, I want to stop users repeating a specific word in a text area on a form. I have a form that allows users to enter text to send in an email, and I want to stop them from saying the word "var1" more than once. Is this possible?

I have tried to do so using the following validation in my model, but this does not work:

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

Aucun commentaire:

Enregistrer un commentaire