0

我有一个描述字段,我想限制为 400 个字符。现在我可以输入文本,计数器显示 [current-count]/400,我可以保存并且一切正常,只要我在 400 限制内。

现在我也可以继续输入超过 400 的限制,然后当我点击保存时,我得到一个错误:

undefined method `each' for nil:NilClass

...加上它列出了一堆参数yadda。我知道这与我的 user.rb 验证有关。

因此,作为测试,当我从user.rb文件中删除验证时:

validates :description, length: { maximum: 400 }

该页面会保存我是否低于或超过限制,而不会出现任何错误消息。但我知道我需要验证。

所以我的目标是我想设置这个,所以我输入type type,计数器计数,一旦我达到400,我就不能再打字了。

那可能吗?我想让它保持简单,而不是尝试在我的文本区域旁边添加消息,例如“您已达到限制”或其他任何内容。我的想法是,这样当用户尝试保存并且计数器显示任何 401/400 时,我不会出现此错误消息问题,因为他们无法输入超过 400。

这足够简单吗?这是我现在拥有的:

在我的 user.rb 中:

validates :description, length: { maximum: 400 }

在我的视图文件中,我有以下 JAVASCRIPT(还包括回车):

<script type="text/javascript">
    $(document).ready(function() {
        $('#char-count').html($('#counted').val().length);
    });

    $('#counted').keyup(function() {
        $('#char-count').html($(this).val().length);
    });
    $('#char-count').html($('#counted').val().replace(/\n/g, "\n\r").length);
    $('#char-count').html($(this).val().replace(/\n/g, "\n\r").length)
</script>

还有我的表单域:

<%= f.label :description, class: "col-sm-3 control-label" %>
<%= f.text_area :description, class: "form-control", id: "counted", rows: 6 %>
<p>Current character count: <span id="char-count">0</span> / 400</p>

任何帮助是极大的赞赏。

4

1 回答 1

1

是的,这是可能的。

您需要为客户端 textarea 验证执行此操作:textarea character limit

您还希望将验证保存在 user.rb 中,以确保保存的描述不超过 400 个字符:

validates :description, length: { maximum: 400 }
于 2015-03-09T07:36:14.780 回答