验证器,密码确认

18

我不明白为什么模型没有检查密码确认,以下是该模型的代码:

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%>

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


3
你需要双重确认验证吗?在密码验证中,你需要指定:confirmation => true - davemyron
1
是的...代码对我也起作用(正如Chamnap所说),而且有一个双重password_confirmation验证器不应该是它不能工作的原因,它只会给你两次“密码不匹配确认”的消息。 - Daniel
2个回答

36

我也曾被这个问题困扰过。我怀疑你的确认值是nil。从文档中可以看出:

注意:只有当 password_confirmation 不为 nil 时,才会执行此检查, 并且默认情况下只在保存时执行。 要求确认,请确保为确认属性添加存在性检查:

此外,你不需要attr_accessor :password_confirmation,因为验证已为你添加了它。Rails!


谢谢 - 这也让我感到有些心烦! - Chip
如何使确认不为空? - Edward

1

如果您正在使用批量赋值,则需要将密码添加到attr_accessible中。 attr_accessor将创建一个虚拟属性,但该属性不可用于批量赋值。 理想情况下,我们不应将password_confirmation添加到attr_accessible中,validates_confirmation_of应验证passwordpassword_confirmation的值,但是password_confirmation的值为空。我将password_confirmation添加到attr_accessible中,它可以正常工作。

使用Rails 3。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接