Sha256: e1f63583ea933367a4d8eedfc1cce9e325f16c8fec20da075d89629fb7ae51d0

Contents?: true

Size: 752 Bytes

Versions: 4

Compression:

Stored size: 752 Bytes

Contents

class AlphaValidator < ActiveModel::EachValidator

  def validate_each(record, attribute, value)
    unless valid?(value.to_s, options)
      record.errors[attribute] << (options.fetch(:message, false) || I18n.t('active_validation.errors.messages.alpha'.freeze))
    end
  end

  private

  def valid_format?(value, options)
    strict = options.fetch(:strict, false)

    value =~ case options.fetch(:case, :any)
    when :lower
      strict ? /^[a-z]+$/ : /^[a-z ]+$/
    when :upper
      strict ? /^[A-Z]+$/ : /^[A-Z ]+$/
    else
      strict ? /^[A-Za-z]+$/i : /^[A-Za-z ]+$/i
    end
  end

  def valid_length?(value)
    value.present?
  end

  def valid?(value, options)
    valid_length?(value) &&
    valid_format?(value, options)
  end

end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
active_validation-2.6.0 lib/active_validation/validators/alpha_validator.rb
active_validation-2.5.0 lib/active_validation/validators/alpha_validator.rb
active_validation-2.4.0 lib/active_validation/validators/alpha_validator.rb
active_validation-2.3.0 lib/active_validation/validators/alpha_validator.rb