How to show input field error message in rails input field

白昼怎懂夜的黑 提交于 2021-01-28 13:50:40

问题


Error message not showing only field highlighted

 <%= f.text_field :website,:required=>true,:pattern=>'https?://.+' %>

How I show that?


回答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 @model do |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:

def some_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.



来源:https://stackoverflow.com/questions/36946608/how-to-show-input-field-error-message-in-rails-input-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!