不允许用户在 rails 的 ruby 中提交包含空字段的表单

Don't allow user to submit a form with empty fields in ruby on rails

我开始在 Rails 上使用 Ruby,但遇到了一些小问题。我有一个包含 3 个字段的表单,这是代码:

<%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
  <%= devise_error_messages! %>

  <div class="field">
    <%= f.text_field :name, autofocus: true, placeholder: "Name" %>
  </div>

  <div class="field">
    <%= f.email_field :email, autofocus: true, placeholder: "Email" %>
  </div>

  <div class="field">
    <%= f.number_field :age, autofocus: true, placeholder: "Age" %>
  </div>

  <div class="actions">
    <%= f.submit "Sign up" %>
  </div>
<% end %>

当您在电子邮件字段中编写非电子邮件内容并尝试提交时,浏览器(chrome 或 firefox )会显示一条错误消息,指出该字段必须包含 @。年龄字段也会发生同样的情况,如果输入字母,浏览器会显示一条错误消息,指出该字段只接受数字。

我想知道如何让浏览器在您尝试提交时任何字段为空时显示一条消息。我知道如何在 cakephp 中完成,所以我想它也可以在 ruby 中完成。我已经验证了模型中的字段,将存在设置为 true 但这仅适用于在您提交并再次重新加载页面后显示消息。

当您使用类似的东西时:

f.email_field

它正在生成一个 HTML5 输入元素,告诉浏览器它必须是有效的电子邮件。 HTML 5 还有一个 required='required' 选项可以用来防止出现空白字段。

你可以这样添加:

<div class="field">
  <%= f.email_field :email, autofocus: true, placeholder: "Email", :required => 'required' %>
</div>

这会将 required='required' 添加到您的表单元素中。请注意,在 HTML5 中,您只需要在表单元素中使用单词 required,但我知道将其添加到 Rails 中的唯一方法是使用我在这里向您展示的选项表单.

这将阻止提交没有该字段的表单。这适用于当前版本的 Firefox、Chrome、Opera 和 IE11。 Safari 将阻止提交但不说明原因。它什么都不做。

我会检查一下:http://blueashes.com/2013/web-development/html5-form-validation-fallback/

HTML 5 有 required=true 选项,可用于防止提交带有空字段的表单。在 rails 表单助手中,您可以像

一样使用它
<%= f.text_field :first_name, required: true %>

<%= f.email_field :email, required: true %>

您可以将 HTML required 属性设置为 true。只需在每个字段中添加 required: true

您的新表单如下所示:

<%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
  <%= devise_error_messages! %>

  <div class="field">
    <%= f.text_field :name, required: true, autofocus: true, placeholder: "Name" %>
  </div>

  <div class="field">
    <%= f.email_field :email, required: true, autofocus: true, placeholder: "Email" %>
  </div>

  <div class="field">
    <%= f.number_field :age, required: true, autofocus: true, placeholder: "Age" %>
  </div>

  <div class="actions">
    <%= f.submit "Sign up" %>
  </div>
<% end %>

您的案例非常定制,这就是它看起来很简单的原因,但您在这里真正想要实现的是 'client-side validation'。

要做到真正便携和用户友好,必须在 JavaScript 中完成。基本上这将是一个脚本,用于验证字段并向用户输出相应的错误消息,同时防止表单提交。这与提交表单时 Rails 在服务器端所做的几乎相同。

定义问题后,您可以通过以下方式之一解决它:

  1. 留在Rails。 Rails 最初设计用于在服务器端处理表单验证。你可以接受它的现状,它会产生最干净、最短和最语义化的代码。为了使其更加无缝,您可以轻松地为其添加一些 AJAX,这应该很容易 (http://guides.rubyonrails.org/working_with_javascript_in_rails.html)。对于用户来说,它看起来就像什么都没有提交一样。

  2. 自己编写一些自定义 JS 来处理这些验证。要么靠你自己,要么借助像 http://jqueryvalidation.org/ 这样的库。这将是一团糟,因为您基本上必须使用不同的语言在客户端复制 Rails 服务器端验证代码。并保持同步。

  3. 使用 Rails 的帮助程序库之一。例如。 https://github.com/joecorcoran/judge 看起来很有前途,但还有其他内容需要 Google 搜索。这些人采用相同的想法:您已获得服务器端验证,并且它们应该可以在客户端轻松使用。某些库会自动生成 JavaScript,其他库只是将要验证的表单发送到后台服务器。

如果我是你,我会选择第一种方式+ AJAX。其他方法会使简单的事情变得不必要的复杂,而不是编写有用的东西,你肯定必须深入调试晦涩的 JS 和神秘的元编程 Ruby/Rails 库。

希望对您有所帮助!