2012-04-18 97 views
1

目前时有验证错误,用class="field_with_errors"一个div获取呈现在我的表格:如何自定义Ruby on Rails验证错误?

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

无需使用额外的宝石,并在Rails 3的环境,是有修改如何验证的方式错误被渲染?例如,我想验证错误divinput标签与错误后呈现:

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

此外,有没有一种方法来呈现一个特定的错误?如果是电子邮件错误,则在输入文本框之后呈现div并产生“重新输入电子邮件”消息。

(大多数到目前为止,我还做了使用宝石作为解决方案。该搜索)

回答

5

1.You可以通过覆盖删除的ActionView的field_with_errors包装:: Base.field_error_proc.It可以通过把这个在做您的config/application.rb中:

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

参考

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

2.You可以显示特定的F错误信息ield。

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

然后在你的CSS

.error { 
    color: red; 
} 
+0

真棒解释soundar! – Goalie 2012-04-18 18:37:01