错误(div class ="fieldWithErrors")解决方法?

New*_*bie 3 ruby-on-rails

在我的项目中,我有一个注册表.

我的HTML看起来像

    <form method="post" action="/users">
<div style="margin: 0pt; padding: 0pt;">
<input type="hidden" value="lDHrKRC2ENhRKcaoBR4XGfzri/MY09PjqVDvHRtC0D4=" name="authenticity_token"/>
</div>    
<p><label for="login">Login</label>
        <input type="text" size="30" name="user[login]" id="user_login"/></p>

        <p><label for="email">Email</label>
        <input type="text" size="30" name="user[email]" id="user_email"/></p>

        <p><label for="password">Password</label>
        <input type="password" size="30" name="user[password]" id="user_password"/></p>

        <p><label for="password_confirmation">Confirm Password</label>
        <input type="password" size="30" name="user[password_confirmation]" id="user_password_confirmation"/></p>

        <p><input type="submit" value="Sign up" name="commit"/></p>
      </form>
Run Code Online (Sandbox Code Playgroud)

现在通过提交空表单生成错误我的代码如下:

    <form method="post" action="/users">
<div style="margin: 0pt; padding: 0pt;"><input type="hidden" value="lDHrKRC2ENhRKcaoBR4XGfzri/MY09PjqVDvHRtC0D4=" name="authenticity_token"/>
</div>    
<p><label for="login">Login</label>
        </p><div class="fieldWithErrors"><input type="text" value="hg" size="30" name="user[login]" id="user_login"/></div>

        <p><label for="email">Email</label>
        </p><div class="fieldWithErrors"><input type="text" value="gh" size="30" name="user[email]" id="user_email"/></div>

        <p><label for="password">Password</label>
        </p><div class="fieldWithErrors"><input type="password" value="gh" size="30" name="user[password]" id="user_password"/></div>

        <p><label for="password_confirmation">Confirm Password</label>
        <input type="password" value="gh" size="30" name="user[password_confirmation]" id="user_password_confirmation"/></p>

        <p><input type="submit" value="Sign up" name="commit"/></p>
      </form>
Run Code Online (Sandbox Code Playgroud)

这将破坏我的布局.有没有解决方案呢

<input type="text" value="gh" size="30" name="user[email]" class="fieldWithErrors" id="user_email"/>
Run Code Online (Sandbox Code Playgroud)

代替

<div class="fieldWithErrors"><input type="text" value="gh" size="30" name="user[email]" id="user_email"/></div>
Run Code Online (Sandbox Code Playgroud)

Joh*_*ley 7

创建一个新的初始化程序,例如/config/initializers/field_error.rb:

ActionView::Base.field_error_proc = Proc.new do |html_tag, instance_tag|
  if html_tag =~ /<(input|textarea|select)[^>]+class=/
    class_attribute = html_tag =~ /class=['"]/
    html_tag.insert(class_attribute + 7, "fieldWithErrors ")
  elsif html_tag =~ /<(input|textarea|select)/
    first_whitespace = html_tag =~ /\s/
    html_tag[first_whitespace] = " class='fieldWithErrors' "
  end
  html_tag  
end
Run Code Online (Sandbox Code Playgroud)