Rails 3: Display validation errors for a form (not saving an ActiveRecord model)

為{幸葍}努か 提交于 2019-12-05 10:59:35

Yes, it can be done fairly easily.

You can use the validations API for it.

As an example, here is a contact us model that I use for an application that is not using ActiveRecord.

class ContactUs
  include ActiveModel::Validations
  include ActiveModel::Conversion
  extend ActiveModel::Naming

  attr_accessor :name, :email, :subject, :message
  validates_presence_of :name, :email, :message, :subject
  validates_format_of :email, :with => /\A[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}\z/
  def initialize(attributes=nil)
    attributes.each do |name, value|
      send("#{name}=", value)
    end unless attributes.nil?
  end

  def persisted?
    false
  end
end

There is a valid method on model, which triggers validation.

so instead model.save, try model.valid?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!