2

我有一个 rails actionMailer 联系表格,它发送电子邮件但不检查它是否不检查表格是否有错误。如果我发送了不正确的电子邮件:ewfw与正确的电子邮件相反:test@test.com 它们都发送,如果表单为空白,则不会发送电子邮件,也不会出现错误消息,但是如果发送了电子邮件,则通知警报会起作用。

任何帮助,将不胜感激。

模型/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

*控制器/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 %>

初始化程序/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 => 'test@test.com',
:password => '#',
:authentication => 'login',
:openssl_verify_mode=>nil,
:enable_starttls_auto => true


}
4

1 回答 1

1

您将需要使用额外的验证器来验证电子邮件的格式是否正确。

它可能看起来像这样:

validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i

更多信息可以在这里找到:http: //apidock.com/rails/ActiveModel/Validations/ClassMethods/validates_format_of

于 2013-02-02T20:13:55.803 回答