Validate Contact Form
-
12-09-2019 - |
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?
Solution
Does this help any? http://forums.site5.com/showthread.php?t=18522
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/