Remove Field name from beginning of the error message in Rails?

572 Views Asked by At

How to remove the model name from the beginning of the error message. while writing custom message for a validation. My validation is like:

validates :phone, presence: {  message: "For security, please enter your <strong> mobile phone number </strong>" }

But the o/p: is like:

Phone For security, please enter your mobile phone number

I want remove the field name ie. phone from the beginning of the error message. I am using Ruby 2.4 with Rails 5.2 please guide with correct syntax to remove it.

1

There are 1 best solutions below

0
On

You should be able to access the hash with the errors. Identifying each validation error with their corresponding column, e.g.:

{:phone=>["For security, please enter your <strong> mobile phone number </strong>"]}

So from there, you can do errors[:phone].first. Make sure of selecting the proper error message. As you have only a presence validation, getting the first element is enough, but might vary.

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