1

我不喜欢 Rails 确认验证如何将消息“不匹配确认”附加到父属性......

validates(:password, {confirmation: true})

从用户体验的角度来看,当两者不匹配时,应该将错误传递给确认“不匹配密码”,这更有意义。

似乎忽略了向确认属性添加任何验证...

validates(:password_confirmation, {my_validation: true, length: {maximum: 3}})

**length验证仅用于测试目的。请注意,此屏幕截图中的密码确认字段没有错误:

表格截图

我创建了一个自定义验证,better_validation

class BetterConfirmationValidator < ActiveModel::EachValidator
  def validate_each(record, attr_name, value)
    parent_attr = attr_name.to_s
    parent_attr['_confirmation'] = ''
    unless value == record.send(parent_attr)
      record.errors.add(attr_name, :better_confirmation, options.merge(:value => value))
    end
  end
end

:password_confirmations但除非我将确认字段命名为不同的名称(即在末尾添加“s”... ),否则它不起作用。

有没有办法告诉 Rails 不要接管并让我对foo_confirmation属性应用验证?

谢谢!

编辑

型号代码...

class User < ActiveRecord::Base
  attr_accessible :name, :email, :password, :password_confirmation
  attr_accessor :password, :password_confirmation

  validates :name,
    presence: true,
    length: { maximum: 50 }
  validates :email,
    presence: true,
    format: { with: /\A.+@[a-z\d\-.]+\z/i },
    uniqueness: true
  validates :password,
    length: { minimum: 6, maximum: 255 },
    presence: { on: :create }
  validates :password_confirmation,
    presence: true,
    better_confirmation: true
.
.
.
end
4

1 回答 1

0

试试看:

validates :password,
  presence: true,
  length: { minimum: 6, maximum: 255 },
  confirmation: true

或者这样:

validate :password_confirmation_match


def password_confirmation_match
  self.errors[:password_confirmation] << "does not match password" if self.password_confirmation.to_s != self.password
end
于 2012-10-29T13:11:04.903 回答