Class: Treaty::Attribute::Option::Validators::RequiredValidator

Inherits:
Base
  • Object
show all
Defined in:
lib/treaty/attribute/option/validators/required_validator.rb

Overview

Validates that attribute value is present (not nil and not empty).

## Usage Examples

Helper mode:

string :title, :required  # Maps to required: true
string :bio, :optional    # Maps to required: false

Simple mode:

string :title, required: true
string :bio, required: false

Advanced mode:

string :title, required: { is: true, message: "Title is mandatory" }

## Default Behavior

  • Request attributes: required by default (required: true)

  • Response attributes: optional by default (required: false)

## Validation Rules

A value is considered present if:

  • It is not nil

  • It is not empty (for String, Array, Hash)

## Advanced Mode

Schema format: ‘{ is: true/false, message: nil }`

Instance Method Summary collapse

Methods inherited from Base

#initialize, #target_name, #transform_value, #transforms_name?

Constructor Details

This class inherits a constructor from Treaty::Attribute::Option::Base

Instance Method Details

#validate_schema!void

This method returns an undefined value.

Validates schema (no validation needed, already normalized)



40
41
42
43
# File 'lib/treaty/attribute/option/validators/required_validator.rb', line 40

def validate_schema!
  # Schema structure is already normalized by OptionNormalizer.
  # Nothing to validate here.
end

#validate_value!(value) ⇒ void

This method returns an undefined value.

Validates that required attribute has a present value

Parameters:

  • value (Object)

    The value to validate

Raises:



50
51
52
53
54
55
56
57
58
59
60
# File 'lib/treaty/attribute/option/validators/required_validator.rb', line 50

def validate_value!(value)
  return unless required?
  return if present?(value)

  message = resolve_custom_message(
    attribute: @attribute_name,
    value:
  ) || default_message

  raise Treaty::Exceptions::Validation, message
end