fix text length validation

completes #64
This commit is contained in:
Mark Moser 2016-09-01 10:37:49 -05:00
parent df1b101aa2
commit a1b93f256d
3 changed files with 36 additions and 27 deletions

View File

@ -1,28 +1,24 @@
$(document).ready(function() {
setTextAreaLimit();
function setTextAreaLimit() {
$.fn.extend({ $.fn.extend({
limiter: function(limit, elem) { characterLimiter: function(limit, $label) {
$('textarea').on("keyup focus show", function() { $(this).on("keyup focus show", function() {
setCount(this, elem); setCount(this, $label);
}); });
function setCount(src, elem) { // TODO: append label container after $this, instead of hard codeing
function setCount(src, $label) {
if(src !== undefined) { if(src !== undefined) {
var chars = src.value.length; var chars = src.value.length;
if (chars > limit) { if (chars >= limit) {
src.value = src.value.substr(0, limit); src.value = src.value.substr(0, limit);
chars = limit; chars = limit;
} }
elem.html(limit - chars); $label.html(limit - chars);
} }
} }
setCount($(this)[0], elem); setCount($(this)[0], $label);
} }
}); });
var elem = $(".chars span"); $(document).ready(function() {
$('textarea').limiter(1000, elem); $('textarea').characterLimiter(1000, $(".chars span"));
}
}); });

View File

@ -6,7 +6,7 @@ class AnswerFormatValidator < ActiveModel::EachValidator
private private
def text record, attribute, value def text record, attribute, value
clean_val = value.to_s.strip clean_val = value.to_s.strip.delete("\r")
return if clean_val.length.between?(1, 1000) return if clean_val.length.between?(1, 1000)
if clean_val.blank? if clean_val.blank?

View File

@ -25,11 +25,24 @@ class AnswerFormatValidatorTest < ActiveSupport::TestCase
assert_match(/enter.*answer/, obj.errors.messages[:answer][0]) assert_match(/enter.*answer/, obj.errors.messages[:answer][0])
end end
test "text should FAIL with more than 1000 charactures" do test "text should PASS with 999 character" do
obj = AnswerValidatable.new('text') obj = AnswerValidatable.new('text')
obj.answer = SecureRandom.urlsafe_base64(1001) obj.answer = long_string_with_returns
assert obj.valid?
assert obj.errors.messages.empty?
end
test "text should FAIL with more than 1000 character" do
obj = AnswerValidatable.new('text')
obj.answer = long_string_with_returns + " - to long now "
refute obj.valid? refute obj.valid?
assert_match(/char.*limit.*1000.$/, obj.errors.messages[:answer][0]) assert_match(/char.*limit.*1000.$/, obj.errors.messages[:answer][0])
end end
def long_string_with_returns
# returns 999 chars, after \r is stripped.
"Some rando input\r\n\rYo. Making this up.\r\n" * 27
end
end end