Nick M
Nick M

Reputation: 2532

Sanitizing user input for a message box

I am developing a crypto-related application and since those people who deal in crypto will always try some sort of scam or script kiddie "hack" I'd like to figure out the best way to clean up content in user-to-user chat boxes and comments fields.

I don't want any HTML/CSS/JS in there.

I want to leave email addresses, URLs, phone numbers and "normal" text untouched.

Right now I am doing a .gsub(/[^0-9a-zA-Z\@\;\:\-\_\,\.\ ]/i, '') before_save but it removes the newlines.

I tried adding .gsub(/[^0-9a-zA-Z\R\@\;\:\-\_\,\.\ ]/i, '') to make it leave newlines alone but it does not seem to work.

Would prefer not having to add any gems.

Upvotes: 2

Views: 1326

Answers (1)

patkoperwas
patkoperwas

Reputation: 1369

Rails has an excellent sanitizer built in, that I would recommend you use instead of trying to figure out your own regular expressions.

See:

http://api.rubyonrails.org/classes/ActionView/Helpers/SanitizeHelper.html

Before you render any user's input out the page wrap it in santize

<%= sanitize @comment.body %>

If you want to sanitize before saving to the database, you can include the helper into your controller

class MyController < ApplicationController
  include ActionView::Helpers::SanitizeHelper

  def create
    content = sanitize(params[:content])
    Thing.save(content: content)
  end
end

Upvotes: 4

Related Questions