Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails, validate maxlength of input field

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
like image 697
finlir Avatar asked Nov 21 '12 15:11

finlir


2 Answers

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.

like image 158
Jon Andersen Avatar answered Oct 09 '22 04:10

Jon Andersen


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

like image 41
Dario Barrionuevo Avatar answered Oct 09 '22 06:10

Dario Barrionuevo