Class: GraphQL::Schema::Validator::FormatValidator

Inherits:
GraphQL::Schema::Validator show all
Defined in:
lib/graphql/schema/validator/format_validator.rb

Overview

Use this to assert that string values match (or don’t match) the given RegExp.

Examples:

requiring input to match a pattern


argument :handle, String, required: true,
  validates: { format: { with: /\A[a-z0-9_]+\Z/ } }

reject inputs that match a pattern


argument :word_that_doesnt_begin_with_a_vowel, String, required: true,
  validates: { format: { without: /\A[aeiou]/ } }

# It's pretty hard to come up with a legitimate use case for `without:`

Constant Summary

Constants included from FindInheritedValue::EmptyObjects

FindInheritedValue::EmptyObjects::EMPTY_ARRAY, FindInheritedValue::EmptyObjects::EMPTY_HASH

Instance Attribute Summary

Attributes inherited from GraphQL::Schema::Validator

#validated

Instance Method Summary collapse

Methods inherited from GraphQL::Schema::Validator

from_config, install, #partial_format, #permitted_empty_value?, uninstall, validate!

Constructor Details

#initialize(with: nil, without: nil, message: "%{validated} is invalid", **default_options) ⇒ FormatValidator

Returns a new instance of FormatValidator.

Parameters:

  • with (RegExp, nil) (defaults to: nil)
  • without (Regexp, nil) (defaults to: nil)
  • message (String) (defaults to: "%{validated} is invalid")


24
25
26
27
28
29
30
31
32
33
34
# File 'lib/graphql/schema/validator/format_validator.rb', line 24

def initialize(
  with: nil,
  without: nil,
  message: "%{validated} is invalid",
  **default_options
)
  @with_pattern = with
  @without_pattern = without
  @message = message
  super(**default_options)
end

Instance Method Details

#validate(_object, _context, value) ⇒ Object



36
37
38
39
40
41
42
43
44
# File 'lib/graphql/schema/validator/format_validator.rb', line 36

def validate(_object, _context, value)
  if permitted_empty_value?(value)
    # Do nothing
  elsif value.nil? ||
      (@with_pattern && !value.match?(@with_pattern)) ||
      (@without_pattern && value.match?(@without_pattern))
    @message
  end
end