I have a comment model where I limit the maximum length of a comment like:
validates_length_of :comment, :maximum => 500
In my view I have input field declared:
<%= f.text_area :comment,:as => :text, :maxlength => 500 %>
The limit on the input field works as expected, it limits to maximum 500 chars.
However, the model limit does not work as expected. A text of 500 chars with newlines gives a validation error. The model counts newlines as two characters (and possible other characters too). So
This input will work, no newlines:
abc abc abc abc....
This will not:
abc
abc
.
.
Is there a simple way to make validates_length_of to count newlines (and other) as one character?.
===Result1===
I combined the great answers from Jon and Dario and created this:
before_validation(:on => :create) do
self.comment = comment.gsub("\r\n","\n") if self.comment
end
Browsers send newlines from textareas as "\r\n" Effectively each newline is counted as two chars when using Rails default length validator
So either make a replace method in the controller, or make a custom length validator.
You could use tokenizer option of the length validator, to count only the words, not the line breaks.
validates :comment, length: {
maximum: 500,
tokenizer: lambda { |str| str.scan(/\w+/) }
}
For more information, take a look here: Active Record Validations and Callbacks
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With