Jake
Jake

Reputation: 1186

Restricting specific words on a form | ruby on rails

I'm implementing a comment section on my blog and was wondering if there was a way to prevent users from submitting a name such as admin or [company name] to prevent people from trolling or otherwise wrong-doing.

I am using this REGEX to validate emails making sure they are properly formatted: VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i

I'm just not sure if this is the same approach I need to be taking or if there are built in ways to prevent specific strings from being entered into a form input.

Thanks in advance for any help!

Upvotes: 0

Views: 513

Answers (3)

jvillegas88
jvillegas88

Reputation: 33

An alternative to what has already been proposed is to create a custom validation on your model with a regular expression.

For example:

validate :bad_words

def bad_words
  if (/admin|sony/i.match(self.name))
    errors.add(:name, "contains a word not allowed")
  end
end

You should generate a regular expression that suits your needs, but it is recommended to use the regexp i modifier to do a case-insensitive search

I hope it helps!

Upvotes: 0

andriy-baran
andriy-baran

Reputation: 739

You can use gem obscenity. It gives you ability to specify black list words and they'll be replaces with [censored] string

Upvotes: 0

Caleb Keene
Caleb Keene

Reputation: 388

There are several ways you could do this, depending on how you want your front-end to behave. The simplest way would be to do the validation in the front-end, either with simple HTML-5 form validation, or with javascript. For HTML-5 validation you can use the pattern attribute on an input type="text" (which you could use a text_field_tag to generate in rails). This attribute accepts a regex as it's value, which you could use to prevent the input of certain key-words. You can read more about this here https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Form_validation

You could also do the validation in the back-end, either in the controller directly (hard to say what exactly you need but something like as a simple example)

if (params[:my_input_form].split & bad_words_array).any?
  flash[:error] = "you entered a bad word"
  redirect_to the_same_page_path
end

note: the & in this context is giving the intersection of the two arrays and will return a non-empty array if there is at least one element in common between the arrays (in this case, if any of the words entered in your input are in the bad_words array).

If you want to do it in the back-end and it's more complicated I would probably move the validation into the model as a custom validator.

Upvotes: 1

Related Questions