Created
October 10, 2012 14:15
-
-
Save noniq/3865897 to your computer and use it in GitHub Desktop.
Rails validator for counting newlines as one character
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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