Class: Incline::SafeNameValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
lib/incline/validators/safe_name_validator.rb

Overview

Validates a string value to ensure it is a safe name.

A safe name is one that only contains letters, numbers, and underscore. It must also start with a letter and cannot end with an underscore.

Constant Summary collapse

VALID_MASK =

Validates a string to ensure it is a safe name.

/\A[a-z](?:_*[a-z0-9]+)*\z/i

Instance Method Summary collapse

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object

Validates attributes to determine if the values match the requirements of a safe name.



16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/incline/validators/safe_name_validator.rb', line 16

def validate_each(record, attribute, value)
  unless value.blank?
    unless value =~ VALID_MASK
      if value =~ /\A[^a-z]/i
        record.errors[attribute] << (options[:message] || 'must start with a letter')
      elsif value =~ /_\z/
        record.errors[attribute] << (options[:message] || 'must not end with an underscore')
      else
        record.errors[attribute] << (options[:message] || 'must contain only letters, numbers, and underscore')
      end
    end
  end
end