定制像github那樣的表單錯誤提示。

引用
app/controllers/application_controller.rb


# 表單驗證錯誤
ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|
	message = case html_tag
		when /<(label)/ 
			%(<div class="error">#{html_tag}</div>).html_safe
		when /<(input|textarea|select)/ 
			if instance.error_message.kind_of?(Array)
				%(#{html_tag}</dd><dd class="error">#{instance.error_message.join('<br />')}).html_safe
			else
				%(#{html_tag}</dd><dd class="error">#{instance.error_message}).html_safe
			end
		end
	message.html_safe
end


引用
app/helpers/layout_helper.rb


module LayoutHelper
  module FormBuilderAdditions
    def error_messages
      if object.errors.any?
        message = I18n.t('activemodel.errors.template.header', 
          :count => object.errors.count, 
          :model => object.class.model_name.human.downcase)
        html = <<-HTML
          <div id='error'>
           <p>#{message}</p>
          </div>
        HTML
        html.html_safe
      end
    end
  end
end
ActionView::Helpers::FormBuilder.send(:include, LayoutHelper::FormBuilderAdditions)


<form accept-charset="UTF-8" action="/people" class="new_person" id="new_person" method="post">
	<div id='error'>
		<p>有 3 個錯誤發生使得「會員」無法被儲存。</p>
	</div>
	<dl>
		<dt><div class="error"><label for="person_profile_name">姓名</label></div></dt>
		<dd><input class="textfield" id="person_profile_name" name="person[profile][name]" size="30" type="text" value="" /></dd>
		<dd class="error">不能是空白字元</dd>
		<dt><div class="error"><label for="person_username">登陸名</label></div></dt>
		<dd><input class="textfield" id="person_username" name="person[username]" size="30" type="text" value="" /></dd>
		<dd class="error">不能是空白字元</dd>
		<dt><div class="error"><label for="person_email">電郵地址</label></div></dt>
		<dd><input class="textfield" id="person_email" name="person[email]" size="30" type="text" value="" /></dd>
		<dd class="error">不能是空白字元</dd>
		<dt><label for="person_password">登陸密碼</label></dt>
		<dd><input class="textfield" id="person_password" name="person[password]" size="30" type="password" /></dd>
		<dt><label for="person_password_confirmation">確認密碼</label></dt>
		<dd><input class="textfield" id="person_password_confirmation" name="person[password_confirmation]" size="30" type="password" value="" /></dd>
		<dd><input id="person_submit" name="commit" type="submit" value="注冊會員" /></dd>
	</dl>
</form>

你可能感兴趣的:(html,Ruby)