Search code examples
ruby-on-railsregexvalidationmodelhyphenation

Rails validations format and changing any other characters into hyphens?


I have this model:

class Tag < ActiveRecord::Base

  # Validations
  validates :name, :presence => true, :uniqueness => true, :format => /[a-z0-9\+\-]+/

end

What I want my app to do is to change every character that is not [a-z0-9\+\-] to be turned into a hyphen. Is this possible, and how? Thanks.


Solution

  • You could use a before filter to convert it pre-validation...

    before_validation :convert_name
    
    def convert_name
      self.name.gsub! /[^a-z0-9\+\-]/, '-'
    end