---
title: "修改ror中error message的样式，让form更好看一些"
author: "yezi"
date: "2007-12-12T17:54:12Z"
tags: []
slug: "ror-error-message-form"
draft: false
lastmod: "2007-12-12T17:54:12Z"
id: 147911
url: "https://yezi.iteye.com/blog/147911"
---

当form提交的时候，我们会在model中定义对输入的数据的校验，一旦出现错误，会显示相应的错误文字。
但是ror在处理的时候有一些问题，如果你对radio这样的form元素进行校验，当数据有问题的时候，页面中radio中的文字会自动折行，显的非常不好看，你可以做如下修改：

打开Configuration中的environment.rb，添加如下程序：

```
ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|
  msg = instance.error_message
  error_style = "background-color: #f2afaf"
  if html_tag =~ /<(input|textarea|select)[^>]+style=/
    style_attribute = html_tag =~ /style=['"]/
    html_tag.insert(style_attribute + 7, "#{error_style}; ")
  elsif html_tag =~ /<(input|textarea|select)/
    first_whitespace = html_tag =~ /\s/
    html_tag[first_whitespace] = " style='#{error_style}' "
  end
  html_tag
end
```


再看看，是不是会好看了一些