Goalie
Goalie

Reputation: 3105

How do you customize Ruby on Rails validation errors?

Currently when there is a validation error, a div with class="field_with_errors" gets rendered in my form:

<form method="post" action="/users" accept-charset="UTF-8">
  <div class="field_with_errors">
    <input id="user_email" type="text" value="[email protected]" name="user[email]">
  </div>
  <input id="user_password" type="password" value="mypass" size="30" name="user[password]">
  <input id="user_submit" type="submit" value="Submit" name="commit">
</form>

Without the use of an additional gem and in a Rails 3 environment, is there a way to modify how the validation error is rendered? For example, I want the validation error div to be rendered after the input tag with the error:

<input id="user_email" type="text" value="[email protected]" name="user[email]"><div class="field_with_errors"></div>

Also, is there a way to render a specific error? If it was an email error, then render the div after the input textbox and produce a "Re-enter your email" message.

(Most of the searches I have done so far use gems as the solution.)

Upvotes: 1

Views: 2212

Answers (1)

Soundar Rathinasamy
Soundar Rathinasamy

Reputation: 6728

1.You can remove the field_with_errors wrapper by overriding ActionView::Base.field_error_proc.It can be done by putting this in your config/application.rb:

config.action_view.field_error_proc = Proc.new { |html_tag, instance| "#{html_tag}".html_safe }

Refer

Rails 3: "field-with-errors" wrapper changes the page appearance. How to avoid this?

2.You can display error message on specific field.

<input id="user_email" type="text" value="[email protected]" name="user[email]">
<% if @user.errors.on(:email).present? %>
   <span class="error">Re-enter your email(or)<%= @user.errors.on(:email) %></span>
<% end %>

Then in your CSS

.error {
  color: red;
}

Upvotes: 5

Related Questions