Question

I have a simple contact form with Subject and Message that I want to validate to prevent blank e-mails.

ActionMailer doesn't support validation. Where should I put it (i.e. in a separated model or directly in controller)?

UPDATE: what is the best way to implement validation in a non ActiveRecord model?

Was it helpful?

Solution

OTHER TIPS

In Rails 3 they decoupled validation from ActiveRecord into ActiveModel. So if you are using Rails or have at least the ActiveModel gem in your project with bundler or whatever your preferred method is you can include ActiveModel::Validations within any class. Here is an example class (note ActiveModel is required for me by Bundler):

class ContactUs::Contact
  include ActiveModel::Validations

  attr_accessor :email, :message

  validates :email,   :format => { :with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i },
                      :presence => true
  validates :message, :presence => true

  def initialize(attributes = {})
    attributes.each do |key, value|
      self.send("#{key}=", value)
    end
    @attributes = attributes
  end

  def read_attribute_for_validation(key)
    @attributes[key]
  end

  def save
    if self.valid?
      ContactUs::ContactMailer.contact_email(self).deliver
      return true
    end
    return false
  end
end

The example comes from a Contact Form Rails 3+ Engine I wrote ContactUs you can browse the code on Github if you run into any other issues with your implementation or use the Gem if it's not too opinionated for your application.

Maybe this helps you: http://activeform.rubyforge.org/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top