Module: CMDx::Validators::Format

Extended by:
Format
Included in:
Format
Defined in:
lib/cmdx/validators/format.rb

Overview

Validates that a value matches a ‘:with` regex and/or does not match a `:without` regex. Both may be combined; at least one is required.

Instance Method Summary collapse

Instance Method Details

#call(value, options = EMPTY_HASH) ⇒ Validators::Failure?

Note:

Non-String values that do not respond to ‘#match?` fail with the regular format failure rather than raise `NoMethodError`. Coerce inputs to String beforehand when format checks are required.

Parameters:

  • value (String, nil)
  • options (Hash{Symbol => Object}) (defaults to: EMPTY_HASH)

Options Hash (options):

  • :with (Regexp)

    must match

  • :without (Regexp)

    must not match

  • :message (String)

    override for the failure message

Returns:

Raises:

  • (ArgumentError)

    when neither ‘:with` nor `:without` is given



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/cmdx/validators/format.rb', line 21

def call(value, options = EMPTY_HASH)
  str = value.nil? || value.respond_to?(:match?) ? value : value.to_s

  match =
    case options
    in with:, without:
      str&.match?(with) && !str&.match?(without)
    in with:
      str&.match?(with)
    in without:
      !str&.match?(without)
    else
      raise ArgumentError, <<~MSG.chomp
        format validator requires :with and/or :without (got #{options.keys.inspect}).
        See https://drexed.github.io/cmdx/inputs/validations/#format
      MSG
    end

  return if match

  Failure.new(options[:message] || I18nProxy.t("cmdx.validators.format"))
end