ActiveAdmin 中字段的输入验证

Input validations on fields in ActiveAdmin

当我在 ActiveAdmin 中创建新表单时,我想要验证我的表单输入字段。但是我找不到相关的教程。我希望有些字段只接受字母,有些只接受数字,有些应该有特定的长度。

f.input :name, :label => "Title", input_html: { autofocus: true }

f.input :description

f.input :email

f.input :contact_number

f.input :contact_person

[不仅要回答 ActiveAdmin,还要回答一般的 RoR]

你应该在 model.

中进行

• 仅限数字:

您希望 :contact_number 为数字,因此您的模型(例如 User)应如下所示:

class User < ActiveRecord::Base

   validates :contact_number, numericality: {only_integer: true}

end

• 最少。 5个字符:

如果描述必须至少包含 5 个字符,则为:

validates_length_of :description, minimum: 5

• 仅限字母:

validates_format_of :name, with: /^[-a-z]+$/

(有关正则表达式的详细信息 --> Validate: Only letters, numbers and -

附加信息:

如果您的表单未通过模型验证,它将 return 警告参数错误(可在 flash[:alert] 数组中访问)。

更多信息请见:

http://guides.rubyonrails.org/active_record_basics.html#validations

您可以在相应的模型中定义验证 class。 See the official documentation for Rails validation.

ActiveAdmin 将在您尝试 create/edit/update 该模型的对象时选择它,如果您有 Rails 标准验证甚至在您的模型中定义的自定义验证 class .

例如,对于您的电子邮件验证,您可以在模型中使用:

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

然后,当您尝试通过 ActiveAdmin create/save 一个对象时,如果电子邮件格式不正确,它会向您显示错误。

因此,您必须在模型中定义所有验证(针对您想要的所有字段)。就是这样!

并且,要显示所有验证错误的列表,您必须执行以下操作:

form do |f|
  f.semantic_errors *f.object.errors.keys
  # ...
end

更新

将这些验证添加到您的模型中 class:

validates_presence_of :description
validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i 
validates :contact_number, :presence => {:message => 'hello world, bad operation!'},
                     :numericality => true,
                     :length => { :minimum => 10, :maximum => 15 }

这些是 Rails 标准验证。您也可以向模型添加自定义验证。

例如,如果您想为 username 添加自定义验证,您可以这样定义:

validate :username_must_be_valid

然后,在同一模型 class 中定义自定义验证器方法 username_must_be_valid,如下所示:

  private

  def username_must_be_valid
    errors.add(:username, 'must be present') if username.blank? && provider.blank?
  end