我不喜欢Rails确认验证如何将“与确认不匹配”的消息附加到父属性...
validates(:password, {confirmation: true})
从UX的角度来看,当两者不匹配时,错误应传递给确认,“密码不匹配”,这更有意义。
将任何验证添加到确认属性似乎都会被忽略......
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
但是除非我将确认字段命名为不同(即在最后加上's'...... :password_confirmations
),否则它不起作用。
有没有办法告诉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
答案 0 :(得分: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