我在使用Twitter引導程序的rails應用程序的初始化程序中具有以下內容,以便在字段上的驗證失敗時刪除rails應用的div.field_with_errors
,而且初始值設定程序將幫助/錯誤的輸入域後,確認文本:使用rails + nokogiri格式化引導程序的表單字段
require 'nokogiri'
ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|
html = %(<div class="field_with_errors">#{html_tag}</div>).html_safe
form_fields = [
'textarea',
'input',
'select'
]
elements = Nokogiri::HTML::DocumentFragment.parse(html_tag).css("label, " + form_fields.join(', '))
elements.each do |e|
if e.node_name.eql? 'label'
html = %(#{e}).html_safe
elsif form_fields.include? e.node_name
if instance.error_message.kind_of?(Array)
html = %(#{e}<span class="help-inline"> #{instance.error_message.join(',')}</span>).html_safe
else
html = %(#{e}<span class="help-inline"> #{instance.error_message}</span>).html_safe
end
end
end
html
end
這工作得很好,但我還需要將.error
類適用於周圍div.control-group
爲每個錯誤。
我初始化當前給出了以下的輸出:
<div class="control-group">
<label class="control-label" for="post_message">Message</label>
<div class="controls">
<input id="post_message" name="post[message]" required="required" size="30" type="text" value="" /><span class="help-inline"> can't be blank</span>
</div>
</div>
,但我需要的東西添加到我的初始化,使其增加了.error
類的div.control-group
像這樣:
<div class="control-group error">
<label class="control-label" for="post_message">Message</label>
<div class="controls">
<input id="post_message" name="post[message]" required="required" size="30" type="text" value="" /><span class="help-inline"> can't be blank</span>
</div>
</div>
該解決方案將可能需要考慮到以下事實:每個驗證錯誤可能有多個標籤和輸入都在同一個div.control-group
之內(例如,單選按鈕/複選框/ 2個文本字段並排) 。
我認爲它需要某種e.at_xpath()
找到div.control-group
家長,並添加.error
類,但我不知道如何做到這一點。
任何人都可以幫忙嗎?
PS這可能都是可能的使用formtastic或simple_form寶石,但我寧願只是使用我自己的html,如果可能的話。
編輯
如果我把e['class'] = 'foo'
在if e.node_name.eql? 'label'
部分則應用類的標籤,所以我想我只是需要找到e
父標籤,然後申請一個.error
類,但我無法弄清楚xpath將從標籤到其父母div.control-group
獲得什麼;沒有點,斜槓或似乎工作的任何組合,但xpath不是我的強項。
謝謝,但我想對於何時更新HTML被輸出js被用戶或用戶提交表單時使用,它在我的js驗證中丟失了某些內容,但被我的服務器端驗證所捕獲。 – user1116573