Reputation: 45
I have a description field that I want to limit to 400 characters. Right now I am able to type in the text, the counter works showing [current-count]/400, and I can save and it all works, as long as I'm within the 400 limit.
Right now I can also keep typing over the limit of 400, and then now when I hit save I get an error:
undefined method `each' for nil:NilClass
...plus it lists a bunch of Parameters yadda. I know this is connected to my user.rb validation.
So just as a test, when I remove the validation from my user.rb file:
validates :description, length: { maximum: 400 }
The page saves whether I'm under or over the limit without any error message. But I know I need the validation.
So my goal is I would like to set this so I type type type, counter counting as it does, and once I hit 400 I can't type anymore.
Is that possible? I'd like to keep it just this simple, rather than trying to add in messages next to my textarea like, "You've reached the limit" or whatever. My thinking is that this way I won't have this error message problem when a user tries to save and the counter shows anything 401/400 because they just can't type over 400.
Is this simple enough to do? Here's what I have right now:
In my user.rb:
validates :description, length: { maximum: 400 }
In my view file I have the following JAVASCRIPT (also includes carriage returns counted):
<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>
And my FORM FIELD:
<%= 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>
Any help is greatly appreciated.
Upvotes: 0
Views: 2159
Reputation:
Yes, it's possible.
You'll want to do this for your client-side textarea validation: textarea character limit
You also want to keep your validation in user.rb to ensure that the description that is saved is not more than 400 characters:
validates :description, length: { maximum: 400 }
Upvotes: 1