Class: Castkit::Validators::StringValidator

Inherits:
Base
  • Object
show all
Defined in:
lib/castkit/validators/string_validator.rb

Overview

Validates that a value is a String and optionally conforms to a format.

Supports format validation using a Regexp or a custom Proc.

Instance Method Summary collapse

Methods inherited from Base

call

Instance Method Details

#call(value, options:, context:) ⇒ void

This method returns an undefined value.

Validates the string value.

Parameters:

  • value (Object)

    the value to validate

  • options (Hash)

    validation options (e.g., ‘format: /regex/` or `format: ->(v) { … }`)

  • context (Symbol, String)

    the attribute name or key for error messages

Raises:



18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/castkit/validators/string_validator.rb', line 18

def call(value, options:, context:)
  return type_error!(:string, value, context: context) unless value.is_a?(::String)
  return unless options[:format]

  case options[:format]
  when Regexp
    raise Castkit::AttributeError, "#{context} must match format" unless value =~ options[:format]
  when Proc
    raise Castkit::AttributeError, "#{context} failed format validation" unless options[:format].call(value)
  else
    raise Castkit::AttributeError, "#{context} has unsupported format validator: #{options[:format].class}"
  end
end