2012-04-18 101 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