Jess
Jess

Reputation: 3151

How to override html formatting in validation errors in Rails?

I'm wondering if there's a way to remove the formatting created by rails validations? My HTML is below, but basically if there's an error it'll format my errors in the built-in rails way... yet I'd like to have it not. For example, in the below, the password_field would be formatted differently in the event of an error (I don't want that), and the error_message would have additional formatting around it when I'd just like the text of the error message to print. Any ideas on how to best do this?

Thanks!

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

Upvotes: 3

Views: 1250

Answers (1)

John Duff
John Duff

Reputation: 38568

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 let you customize the html for the errors however you would like.

This example will leave the html form field exactly 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 to render the 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

I basically just stripped down what the normal error_message_on does for what you need.

Now you can use it in your page like so:

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

and the html output will be something like this:

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

This will let you put whatever extra markup you need and wont restrict you to doing it one way for all your forms.

Another thing you might want to take a look at if you have a number of forms that follow the same pattern is the custom form builders http://ramblingsonrails.com/how-to-make-a-custom-form-builder-in-rails.

Upvotes: 7

Related Questions