Netskin Logo

Validation on String Inputs in Rails

#rails
by Ingo Albers on 05.08.2022

Input validation is important because it prevents improperly formed data from entering into a database. Bad data could lead to unexpected behaviour like displaying errors when the data is being presented or in the worst case could even provide a potential attack vector for hackers.

To prevent this, we introduced a simple validator using Regexp, which ensures that only a specific subset of characters is allowed for a string input.

In our example we allow \w, which matches alphanumeric characters A-Z, a-z and 0-9, which can also be written as [:word]. We also allow some specific other characters (_, -, @, +, . and any whitespace character, represented by \s). Any validator under app/validators/ will automatically be picked up and loaded by Rails.

# app/validators/whitelisted_characters_validator.rb
class WhitelistedCharactersValidator < ActiveModel::EachValidator
  def self.valid?(value)
    value =~ /^[\w-_@+’'`\s\.]*$/
  end

  def validate_each(record, attribute, value)
    return if value.nil?
    return if self.class.valid?(value)
    record.errors.add(attribute, options[:message] || proc{ I18n.t("validation_error.contains_invalid_chars")})
  end
end

We can then easily use this validator on any of our form objects or models directly by using the validates method.

validates :filename, whitelisted_characters: true

Like this we can make sure that no data with unspecified characters can be saved or processed in the application. This increases the security and maintainability of the application.

Happy Coding!

Resources

❮ How to Use Heredoc in Ruby
Pattern matching and deconstructing ❯
Netskin Logo