Search code examples
ruby-on-railsvalidationacts-as-taggable-on

custom validations with acts-as-taggable-on


Hi I am working on a Rails 3 project and I am using acts-as-taggable-on and everything works perfectly! :)

I just have one question.

Does anyone know how I can add my 'custom' validation to ActsAsTaggableOn::Tag? Any callbacks I can hook into (e.g before_tag_save)? or something similar?

I need to run a regex on each 'tag' (to ensure that each tag does not contain any illegal characters) in my tag_list before I save my model and would like to know if there is a standard way of doing it.

The way I solved the problem is by adding a validation method in my PostController which just iterates over the list of Tags and runs the regex, but this seems ugly to me.

Any suggestions?

Thank you in advance! :)


Solution

  • I used two ways in the past. One via a custom validator, another with a validates call.

    Custom Validation method

    In your model, setup the following

      validate :validate_tag
    
      def validate_tag
        tag_list.each do |tag|
          # This will only accept two character alphanumeric entry such as A1, B2, C3. The alpha character has to precede the numeric.
          errors.add(:tag_list, "Please enter the code in the right format") unless tag =~ /^[A-Z][0-9]$/
        end
      end
    

    Obviously you will need to replace the validation logic and the error message text with something more appropriate in your circumstance.

    Keep in mind that in this scenario you can evaluate each tag as a string.

    Standard Validation Method

    Include this in your model

    validates :tag_list, :format => { :with => /^([A-Z][0-9],?\s?)*$/,
          :message => "Just too awesomezz" }
    

    With this method, you will have to keep in mind that you are validating the entire array that looks like a string. For this reason, you will need to allow for commas and white spaces between the tags.

    Choose whichever method suits you most