ActionMailer和Validations

时间:2013-02-02 18:39:41

标签: ruby-on-rails validation actionmailer

我有一个rails actionMailer联系表单,它发送电子邮件但不检查是否不检查表单是否有错误。 如果我发送了错误的电子邮件:ewfw而不是正确的电子邮件:test@test.com 他们都发送,如果表单是空白的,则不会发送电子邮件,也不会出现错误消息,但是如果发送电子邮件,则通知alart有效。

任何帮助将不胜感激。

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

*视图/支撑/ 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


}

1 个答案:

答案 0 :(得分: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