如何防止用户将空格输入到rails文本字段

时间:2017-06-29 18:20:24

标签: javascript jquery ruby-on-rails ruby

我有一个rails应用程序来渲染表单并接受三个输入。我不希望用户能够在字符之间输入空格。我是铁路新手,不知道从哪里开始。这是我的表格:

  <%= form_for :article, url: articles_path do |f| %>
    <p>
       <%= f.label :IP , "IP Address" ,  class: "input-lg"%><br>
       <%= f.text_field :IP , class: "form-control"%>
    </p>

    <p>
       <%= f.label :Email , class: "input-lg"%><br>
       <%= f.text_field :Email , class: "form-control"%>
    </p>
    <p>
       <%= f.label :Device , class: "input-lg"%><br>
       <p>
          <%= f.select :Device , [['Server'],['Network']] %>
       </p>
   </p>
   <p>
      <%= f.submit "Submit", class: "btn btn-default"%>
   </p>
 <% end %>

我确信有一种方法可以使用JavaScript或JQuery,但我不太熟悉如何在Rails中使用JQuery或者我是如何使用JavaScript的。

1 个答案:

答案 0 :(得分:1)

由于您希望在输入时执行此操作,因此您需要使用Javascript或Jquery。我将不再讨论如何启用和调试该部分,只需检查一些现有的指南,因为它们很多。

对于检查的实际方式,您需要: - 知道用户何时在您要限制的输入字段之一中键入内容; - 阻止或替换受限制的输入。

完成它的最简单方法是通过传递输入选择器将“keyup”事件绑定到要定位的输入字段。在这种情况下,IP和电子邮件。

       $("input[name='IP'], input[name='Email'").keyup(function(e) {
          var value = $(this).val(); 
    //read the value - jquery will pass the element that is triggering the event as -this- so you can get it by using $(this)
          value = value.replace(/\s+/g, ''); 
//replace all whitespaces by nothing, effectively removing them
          $(this).val(value); 
//assign the stripped of whitespace value to the val attribute of to the input field
        });

这可以变得更加复杂,只接受特定的模式,只接受数字等,但可能性几乎无穷无尽。

相关问题