使用foundation-beat验证文本字段的长度

Use foundation abide to validate length of a text field?

本文关键字:字段 文本 foundation-beat 验证 使用      更新时间:2023-09-26

我正在rails应用程序中使用foundation,我正在寻找一种验证表单中文本字段长度的方法:当文本字段包含太多字符时(但当它为空时),我希望显示错误。

我尝试使用Foundation的遵守并创建自定义命名模式,如文档中所述。

以下是我的application.js文件的内容,包括Foundation初始化时的自定义模式:

$(function(){ 
  $(document)
    .foundation()
    .foundation('abide', {
      patterns: {
        short_field: /^.{,40}$/,
        long_field: /^.{,72}$/
      }
    }); 
});

这是我在视图中的表单代码:

<form data-abide>
  <div class="long-name-field">
    <input type="text" pattern="long_field" placeholder="Long Field">
    <small class="error">Too long.</small>
  </div>
  <div class="short-name-field">
    <input type="text" pattern="short_field" placeholder="Short Field">
    <small class="error">Too long.</small>
  </div>
</form>

问题是,当我加载表单页面时,所有字段总是显示错误消息,无论它们是空的、在字符限制下填充的还是超过字符限制的。

有人成功地使用了遵守来做类似的事情(或者知道不使用自定义命名模式的更好方法)吗?

干杯。

我终于成功了!

问题是/^.{,40}$/不是有效的regexp语法,您必须显式使用/^.{0,40}$/

我把它误认为是/.{5,}/语法,您可以使用它来施加一个下限。

我无法让javascript在我的Rails 4应用程序中正常工作,所以我只是直接添加regex作为属性,如下所示:

<%= text_area_tag 'answer', @current_answer,
        :placeholder => 'required', :required => '', :pattern => '^(.){0,1000}$' %>

对于验证最小长度,我只使用:

<%= text_area_tag 'answer', @current_answer,
        :placeholder => 'required', :required => '', :pattern => '^(.){100,}$' %>