【问题标题】:Validators, password confirmation验证器,密码确认
【发布时间】:2011-06-09 12:17:21
【问题描述】:

我不明白为什么模型不检查密码确认,这是模型的代码:

class User < ActiveRecord::Base
  attr_accessor :password_confirmation
  validates :email, :presence =>true,
                    :uniqueness=>true
  validates :password, :presence =>true,
                    :length => { :minimum => 5, :maximum => 40 },
                    :confirmation =>true
  validates_confirmation_of :password
end

控制器旨在从视图中获取数据并尝试执行保存,这是视图的代码:

<h1>Registration process</h1>
<%= form_for(@new_user) do |f|%>
<% if @new_user.errors.any? %>
  <div id="errorExplanation">
    <h2><%= pluralize(@new_user.errors.count, "error") %> prohibited this article from being saved:</h2>
    <ul>
    <% @new_user.errors.full_messages.each do |msg| %>
      <li><%= msg %></li>
    <% end %>
    </ul>
  </div>
  <% end %>
    <%= f.label :email %><br />
    <%= f.text_field :email %><br />
    <%= f.label :password %><br />
    <%= f.password_field :password %><br />
    <%= f.label :password_confirmation %><br />
    <%= f.password_field :password_confirmation %>
    <%#TODO Confirm password%>

    <%= f.submit 'Join' %>
<%end%>

如果密码不匹配,不会出现错误。

【问题讨论】:

  • 是否需要双重确认验证?您在密码验证中指定:confirmation =&gt; true
  • 是的......该代码也适用于我(正如 Chamnap 所说)并且拥有双重密码确认验证器不应该是它不起作用的原因。它只会给你两次消息“密码与确认不符”

标签: ruby-on-rails-3 validation password-confirmation


【解决方案1】:

我也被这个烫伤了。我怀疑您的确认值是nil。来自文档:

注意:此检查仅在以下情况下执行 password_confirmation 不为零,并且 默认情况下仅在保存时。要求 确认,请确保添加一个 存在检查以进行确认 属性:

另外,您不需要attr_accessor :password_confirmation,因为验证会为您添加它。导轨!

【讨论】:

  • 谢谢 - 这也让我有些胃灼热!
  • 我怎样才能使确认不为零?
【解决方案2】:

如果您使用的是批量分配,则需要将密码添加到attr_accessibleattr_accessor 将创建一个虚拟属性,但不能用于批量分配 理想情况下,我们不应该将password_confirmation 添加到attr_accessiblevalidates_confirmation_of 应该验证passwordpassword_confirmation 的值,但password_confirmation 的值将为零。我将password_confirmation 添加到 attr_accessible 并且它工作正常

使用 Rails 3。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-18
    • 2015-04-03
    • 2023-02-23
    • 2011-08-23
    • 2017-12-06
    • 2021-07-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多