How to override html formatting in validation errors in Rails?

I am wondering if there is a way to remove the formatting created by checking rails? My HTML is lower, but basically, if there is an error, it will format my errors in the built-in rails ... but I would like for me not to have this. For example, in the password_field field below, it will be formatted differently in case of an error (I don’t want this), and error_message will have additional formatting around it when I just like the text of the error message Print. Any ideas on how best to do this?

Thank!

- <% = f.password_field: password%>
<% = error_message_on: user,: password%> -

+3
source share
1 answer

Take a look at this link in the rails guide http://guides.rubyonrails.org/active_record_validations_callbacks.html#customizing-error-messages-css . This should allow you to configure html for errors, but you would like to.

In this example, the html form field will be the same even if there are errors.

ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|
  %(#{html_tag})
end 

Next, we can add a helper method for visualizing errors:

def custom_error_message_on(object, method)
  errors = object.errors.on(method)
  "#{ERB::Util.html_escape(errors.is_a?(Array) ? errors.first : errors)}"
end

Basically, I just stripped, which makes a normal error_message_on for what you need.

Now you can use it on your page like this:

<%= f.password_field :password %>
<%= custom_error_message_on :user, :password %>

and the html output would be something like this:

<input type='password' name='password' />
Your password is required

This will allow you to place any additional markup you need, and will not limit you to one way for all your forms.

, , , , , , - http://ramblingsonrails.com/how-to-make-a-custom-form-builder-in-rails.

+7

Source: https://habr.com/ru/post/1728707/


All Articles