Skip to content

Instantly share code, notes, and snippets.

@noniq
Created October 10, 2012 14:15
Show Gist options
  • Save noniq/3865897 to your computer and use it in GitHub Desktop.
Save noniq/3865897 to your computer and use it in GitHub Desktop.
Rails validator for counting newlines as one character
# Browsers send newlines from textareas as "\r\n", thus each newline is counted
# as two chars when using Rails’ default LengthValidator.
#
# Of course it would also be possible to convert "\r\n" to "\n" in the controller
# or model, but in my app it’s simpler do use a custom validator.
class LengthCountingNewlinesAsOneValidator < ActiveModel::Validations::LengthValidator
def validate_each(record, attribute, value)
value = value.gsub("\r\n", "\n")
super
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment