【问题标题】:Reset Password Validation Error: Password is too short error even though password is within range重置密码验证错误:密码太短错误,即使密码在范围内
【发布时间】:2012-05-23 14:20:39
【问题描述】:

最近,我将我的密码验证代码更改为下面的代码,这样我就可以创建一个不需要密码和密码确认的表单How to only change one attribute in a model using form_for in Rails。

请注意,我没有使用 has_secure_password 来生成我的加密密码。我在 RailsTutorial 中使用了每个 Hartl 的 SHA2.hexdigest。

用户.rb

before_save :encrypt_password, :unless => Proc.new { |u| u.password.blank? }
validates_presence_of :password, :if => :should_validate_password?
validates_confirmation_of :password, :if => :should_validate_password?
validates_length_of :password, :minimum => 6, :maximum => 40, :allow_blank => true
#changing :allow_blank from false to true above fixed my problem.

def should_validate_password?
  updating_password || new_record?
end

我在记住我/重置密码http://railscasts.com/episodes/274-remember-me-reset-password 上关注了这个 Railscast,但我一直收到这个错误:

ActiveRecord::RecordInvalid in PasswordResetsController#create

Validation failed: Password is too short (minimum is 6 characters)

当我尝试为现有用户生成 auth_tokens 以及尝试提交我的电子邮件以获取重置链接时再次发生这种情况。我可以通过注释掉这段代码来暂时删除这个验证,一切正常。

我尝试重新登录用户帐户以更改密码,使其在范围内(9 个字符长),但我仍然收到相同长度的验证错误消息。

有什么建议吗?

我不知道问题出在哪里。我不明白为什么要验证我的密码。

这是我在密码重置控制器中的创建操作:

def create
  user = User.find_by_email(params[:email])
  user.send_password_reset if user
  redirect_to root_path, :notice => "Email sent with password reset"
end

这是我的密码重置表格:

<%= form_tag password_resets_path, :method => :post do %>
  <div class="field">
    <%= label_tag :email %>
    <%= text_field_tag :email, params[:email] %>
  </div>
  <div class="actions"><%= submit_tag "Reset Password" %></div>
<% end %>

如果你们需要任何其他文件,请告诉我。

编辑:使用可行的解决方案对代码进行了更改。

谢谢。

【问题讨论】:

  • 解决了。 :allow_blank =&gt; true 会成功的。

标签: ruby-on-rails ruby-on-rails-3


【解决方案1】:

出现错误是因为您验证了 password_confirmation。这意味着它也将期望一个范围内的值。

您可以通过以下方式解决此问题:

validates :password,  length:     { minimum: 8, allow_nil: true },
                      confirmation: true

【讨论】:

    【解决方案2】:

    您不需要 :should_validate_password?

    我刚刚添加了一个 Proc,如下所示:

    validates :password, length: { minimum: 6 }, unless: Proc.new { |user| user.password.nil? }
    validates :password_confirmation, presence: true, unless: Proc.new { |user| user.password.nil? }
    

    或者您可以使用 with_options 对其进行分组

    见:http://guides.rubyonrails.org/v3.2.13/active_record_validations_callbacks.html

    【讨论】:

      猜你喜欢
      • 2016-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-27
      • 2016-07-11
      • 2017-08-02
      • 2013-09-21
      相关资源
      最近更新 更多