【问题标题】:form validation with simple_form and html5使用 simple_form 和 html5 进行表单验证
【发布时间】:2012-07-01 18:46:06
【问题描述】:

我们页面的简单方法是 Welcome-controller 添加电子邮件 -> second_controller 使用电子邮件地址创建一个新对象。

我们有一个显示欢迎页面的欢迎控制器。在此页面上,您可以键入一个电子邮件地址,该地址将提供给其他控制器。我们使用 simple_form 如果我们输入这个config.browser_validations = false 并输入“正常”文本,我们会在创建操作时收到错误。在旧版本中,如果没有 simple_form,我们会收到验证错误。 如果我们启用它,我们将获得 html5 验证。但是当浏览器不支持 html5 时呢? 我们的模型在这里

validates :owner_email,   
        :presence => true,
        :format => { :with => /\A[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]+\z/ },
        :on => :create

我们的欢迎视图在这里

<p>
<h2>Create a list without registration.</h2>
<%= simple_form_for([@list], :html => {:class => 'well' }) do |f| %>
    <%= f.input :owner_email,  :label => false, :placeholder => 'Your Email.' %>
      <%= f.button :submit, "Create", :class => "btn-primary" %>
<% end %>
</p>

第二个控制器的创建动作是这样的

def create
# create a new list and fill it up
# with some default values
  @list = List.new(
    :title => "List", 
    :description => "Beschreibung",
    :owner_email => "test@domain.com",
    :admin_key => generate_admin_key)
  @list.update_attributes(params[:list])
  respond_with(@list) do |format| 
    format.html {#
      redirect_to :action => "admin", :id => @list.access_key, :status => 301}
  end 
end

如果我们在 html4 版本中收到错误消息,我们需要进行哪些更改?大家可以帮帮我们吗?

【问题讨论】:

    标签: ruby-on-rails ruby html validation simple-form


    【解决方案1】:

    只需添加一个 :message 参数。除非您更改了 simple_form 配置,否则消息错误应显示在错误字段的右侧。

    validates :owner_email,   
            :presence => true,
            :format => { :with => /\A[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]+\z/ ,
                         :message => 'Invalid e-mail! Please provide a valid e-mail address'},
            :on => :create
    

    【讨论】:

    • Unknown validator: 'MessageValidator' 谢谢,但现在我在欢迎页面上收到消息验证错误。我要改变看法吗?
    • :message - 块是必需的 :format .block :format =&gt; { :with =&gt; /\A[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]+\z/, :message =&gt; 'Invalid e-mail! Please provide a valid e-mail address' },
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-09
    • 2013-09-28
    • 1970-01-01
    • 2013-02-28
    • 2019-04-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多