Module: CMDx::Validators::Format

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

Overview

Validates that a value matches a specified format pattern

This validator ensures that the given value conforms to a specific format using regular expressions. It supports both direct regex matching and conditional matching with inclusion/exclusion patterns.

Instance Method Summary collapse

Instance Method Details

#call(value, options = {}) ⇒ nil

Validates that a value matches the specified format pattern

Examples:

Direct regex validation

Format.call("user@example.com", /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i)
# => nil (validation passes)

Validate with required pattern

Format.call("ABC123", with: /\A[A-Z]{3}\d{3}\z/)
# => nil (validation passes)

Validate with exclusion pattern

Format.call("hello", without: /\d/)
# => nil (validation passes - no digits)

Validate with both patterns

Format.call("test123", with: /\A\w+\z/, without: /\A\d+\z/)
# => nil (validation passes - alphanumeric but not all digits)

Validate with custom message

Format.call("invalid", with: /\A\d+\z/, message: "Must contain only digits")
# => raises ValidationError with custom message

Parameters:

  • value (Object)

    The value to validate for format compliance

  • options (Hash, Regexp) (defaults to: {})

    Validation configuration options or direct regex pattern

Options Hash (options):

  • :with (Regexp)

    Required pattern that the value must match

  • :without (Regexp)

    Pattern that the value must not match

  • :message (String)

    Custom error message

Returns:

  • (nil)

    Returns nil if validation passes

Raises:

  • (ValidationError)

    When the value doesn’t match the required format



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/cmdx/validators/format.rb', line 43

def call(value, options = {})
  match =
    if options.is_a?(Regexp)
      value&.match?(options)
    else
      case options
      in with:, without:
        value&.match?(with) && !value&.match?(without)
      in with:
        value&.match?(with)
      in without:
        !value&.match?(without)
      else
        false
      end
    end

  return if match

  message = options[:message] if options.is_a?(Hash)
  raise ValidationError, message || Locale.t("cmdx.validators.format")
end