Reputation: 117
let say that I have set in model for validation like this
validates :tel, presence: true , length: { minimum: 10, maximum: 11 }, numericality: { only_integer: true }
how do I can display a custom message in view for each validate.
when I set this in views page.
<% if @diary.errors.include?(:tel) %>
<div class="err"><p><%= @diary.errors.full_messages_for(:tel).join("") %></p></div>
<% end %>
it directly displays all error message. I want to make a display in view like this
if(error_require)
echo "tel is needed"
else if(error_length)
echo "tel is to long"
else
echo "tel must numeric"
end
can I make like that?
Upvotes: 0
Views: 1072
Reputation:
One way to do this is to define methods for each type of validation (in your model) like this:
validate :chech_length
def chech_length
if tel.length < 10 || tel.length > 11
errors.add(:base, "tel is too long!")
end
end
validate :check_if_present
def check_if_present
if tel.blank?
errors.add(:base, "tel must be present!")
end
end
etc...
Hope this helps.
Upvotes: 1
Reputation: 4920
You can pass message
in separate hashes for each validator:
validates :tel,
presence: { message: 'is needed' },
length: { minimum: 10, maximum: 11, too_long: 'is too long' },
numericality: { only_integer: true, message: 'must be numeric' }
Read more about presence, length, and numericality validators.
Upvotes: 3