Class: Validatious::Validators::TextContentValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
lib/validatious/validators/text_content_validator.rb

Overview

Active Model Text Content Validator

Instance Method Summary collapse

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/validatious/validators/text_content_validator.rb', line 6

def validate_each(record, attribute, value)
  return if value.nil?
  
  error = false
  
  # The text should start with a capital letter
  error = true if value.match(/[A-Z]/).nil?
  
  # The text should contain at least one punctuation mark
  error = true if value.match(/[\.?!]/).nil?
  
  # There should be at least one 'e' per 30 characters
  error = true if value.downcase.count('e') < (value.downcase.gsub(/[^a-z]*/, '').length / 30)
  
  # There should be at least one space per 20 characters
  error = true if value.downcase.count(' ') < (value.length / 20)
  
  # The text should be at least 25% lowercase
  error = true if value.gsub(/[^a-z]*/, '').length < (value.downcase.gsub(/[^a-z]*/, '').length / 4)
  
  record.errors.add(attribute, :invalid_text_content, options) if error
end