Skip to content Skip to sidebar Skip to footer

How To Show Input Field Error Message In Rails Input Field

Error message not showing only field highlighted <%= f.text_field :website,:required=>true,:pattern=>'https?://.+' %> How I show that?

Solution 1:

Option 1 (recommended): use simple_form gem. It makes it easy to display error messages next to the fields. After installing the gem, you can then simply do this:

<%= f.input :website %>

Option 2: code it yourself. Something like the following would be a start. You'll probably want to add some CSS classes for styling, and decide what to do if multiple errors are present on the field.

<%= form_for @modeldo|f| %>
  <%= f.text_field :website %>
  <%= @model.errors.full_messages_for(:website).join(', ') if@model.errors.has_key?(:website) %>
<% end %>

Side note

The above won't work if @model does not have validation errors associated with the website field. This is typically not a concern with Rails built-in validations. I.e., if you do something like validates_presence_of :website - you're good. But if you have custom validations, make sure to add the errors on the website field when calling errors.add, like:

defsome_custom_validator
  errors.add(:website, 'Something is wrong') if some_logic
end

If your Rails or custom validations add errors on :base instead (errors.add(:base, 'some global issue'), you may also want to have some global errors displayed at the top as described here.

Post a Comment for "How To Show Input Field Error Message In Rails Input Field"