[英]Rails 4: remove attribute name from error message in custom validator
[英]Remove Field name from beginning of the error message in Rails?
如何从错误消息的开头删除模型名称。 在编写自定义消息进行验证时。 我的验证是这样的:
validates :phone, presence: { message: "For security, please enter your <strong> mobile phone number </strong>" }
但是 o/p: 就像:
电话 为安全起见,请输入您的手机号码
我想删除字段名称,即。 电话从错误信息开始。 我将 Ruby 2.4 与 Rails 5.2 一起使用,请使用正确的语法指导将其删除。
您应该能够访问带有错误的哈希。 用相应的列标识每个验证错误,例如:
{:phone=>["For security, please enter your <strong> mobile phone number </strong>"]}
所以从那里,你可以做errors[:phone].first
。 确保选择正确的错误消息。 由于您只有一个存在验证,因此获取第一个元素就足够了,但可能会有所不同。
foo = User.new
foo.valid? # false
foo.errors
# => #<ActiveModel::Errors:0x00007f80d52ff2a8
# @base=#<User:0x00007f80d52c4bd0 id: nil, phone: nil, created_at: nil, updated_at: nil ...>,
# @details={:phone=>[{:error=>:blank}]},
# @messages={:phone=>["For security, please enter your <strong> mobile phone number </strong>"]}>
foo.errors[:phone]
# => ["For security, please enter your <strong> mobile phone number </strong>"]
foo.errors[:phone].first
# => "For security, please enter your <strong> mobile phone number </strong>"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.