Reputation: 427
I have a rails actionMailer contact form which send emails but doesn't check if it dosen't check the form for errors.
If I send an incorrect email: ewfw
as opposed to a correct email: [email protected]
they both send, if the form is blank no email will get sent, and no error message comes up as well, but the notification alart works if the email get sent.
Any help would be appreciated.
models/support.rb
class Support
include ActiveModel::Validations
validates_presence_of :email, :sender_name, :support_type, :content
# to deal with form, you must have an id attribute
attr_accessor :id, :email, :sender_name, :support_type, :content
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 to_key
end
def save
if self.valid?
Notifier.support_notification(self).deliver!
return true
end
return false
end
end
*controllers/supports_controller.rb*
class SupportsController < ApplicationController
def new
# id is required to deal with form
@support = Support.new(:id => 1)
end
def create
@support = Support.new(params[:support])
if @support.save
redirect_to('/contact', :notice => "Your message was successfully sent.")
else
flash[:alert] = "You must fill all fields."
render 'new'
end
end
end
*views/support/form_.html.erb*
<% form_for @support, :url => { :action => "create" }, :html => { :method => :post } do |f| %>
<p>
<%= f.label "Name" %>
</p>
<p>
<%= f.text_field :sender_name, "size" => 37 %>
</p>
<p>
<%= f.label "Email" %>
</p>
<p>
<%= f.text_field :email, "size" => 37 %><br /><br />
</p>
<p>
<%= f.label "Subject" %>
</p>
<p>
<%= f.select :support_type, options_for_select(["Hire", "General", "Collaboration"]) %>
</p>
<p>
<%= f.label "Details" %>
</p>
<p>
<%= f.text_area :content, "rows" => 3, "cols" => 27 %>
</p>
<p><br />
<%= f.submit "Submit" %>
</p>
<% end %>
Initializers/mailer.rb
# config/initializers/mailer.rb
ActionMailer::Base.delivery_method = :sendmail
ActionMailer::Base.perform_deliveries = true #default value
ActionMailer::Base.raise_delivery_errors = true
ActionMailer::Base.sendmail_settings = {
:tls => true,
:address => 'smtp.test.com',
:port => 587,
:domain => 'test.com',
:user_name => '[email protected]',
:password => '#',
:authentication => 'login',
:openssl_verify_mode=>nil,
:enable_starttls_auto => true
}
Upvotes: 2
Views: 1550
Reputation: 1355
You will want to use an additional validator to validate that the email is in the proper format.
It could look something like this:
validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i
More information can be found here: http://apidock.com/rails/ActiveModel/Validations/ClassMethods/validates_format_of
Upvotes: 1