views:

280

answers:

1

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 %>-

+5  A: 

Take a look at this link in the rails guide http://guides.rubyonrails.org/activerecord_validations_callbacks.html#customizing-the-error-messages-html. 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.

John Duff
thanks, John - to add to my questions, though: What if I have extra HTML that I want to put between the form and the error, and that HTML will differ from form to form? In the above example, it requires me to put a <br> between input box and error, but in my application, what's in between will be different for each form.
Jess
I've updated the answer based on your comments, hopefully that helps.
John Duff