【问题标题】:Rails: Simple-Form & Devise: mark email field of user model as required in forms automatically?Rails:Simple-Form&Devise:自动在表单中将用户模型的电子邮件字段标记为必需?
【发布时间】:2015-03-30 15:26:58
【问题描述】:

我想知道为什么 email 字段在 Simple-Form 中没有标记为必填字段,因为当提交为空时会出现验证错误“不能为空”。

email 字段的验证规则似乎来自 Devise,因此它们可用于验证机制,但不适用于 Simple-Form。这是为什么呢?

我可以简单地将另一个validates :email, presence: true 添加到我的User 模型中,但这似乎有点过头了。或者我可以在 Simple-Form 的 f.input :email 方法中添加一个 required: true,但这似乎也有点矫枉过正。

这是我的User 模型的相关部分:

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable,
         :confirmable, :lockable, authentication_keys: [:login]

  validates :name, presence: true

我的配置是否不正确/不完整?

【问题讨论】:

    标签: ruby-on-rails forms validation devise simple-form


    【解决方案1】:

    来自简单表单的README

    出于性能原因,在验证时会跳过此检测 使用条件选项,例如 :if 和 :unless。

    您可以看到,Devise 将在 https://github.com/plataformatec/devise/blob/master/lib/devise/models/validatable.rb 中添加带有 :if 的验证

        base.class_eval do
          validates_presence_of   :email, if: :email_required?
          validates_uniqueness_of :email, allow_blank: true, if: :email_changed?
          validates_format_of     :email, with: email_regexp, allow_blank: true, if: :email_changed?
    
          validates_presence_of     :password, if: :password_required?
          validates_confirmation_of :password, if: :password_required?
          validates_length_of       :password, within: password_length, allow_blank: true
        end
    

    因此,您必须在视图中根据需要标记该字段。

    【讨论】:

      【解决方案2】:

      如果您提交空白,它将显示要求您填写该字段, 如果您提交错误的电子邮件,将要求您提供有效的电子邮件。

      所以它首先检查空白,如果不是空白则检查是否有效。

      您的表单运行良好。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-08
        • 2015-08-10
        • 1970-01-01
        • 2011-10-20
        • 2020-11-17
        • 1970-01-01
        • 2012-05-03
        • 1970-01-01
        相关资源
        最近更新 更多