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

Inherits:
Validator
  • Object
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

Example: requiring input to match a pattern

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

Example: 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:`

Instance Method Summary collapse

Constructor Details

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

Parameters

  • with (RegExp, nil)
  • without (Regexp, nil)
  • message (String)

:call-seq:

initialize(RegExp | nil with:, Regexp | nil without:, String message:, **default_options)

: (?with: Regexp | Proc | nil, ?without: Regexp | Proc | nil, ?message: String | Proc, **untyped default_options) -> void



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

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

Instance Method Details

#validate(_object, _context, value) ⇒ Object

: (untyped _object, GraphQL::Query::Context _context, untyped value) -> String?



50
51
52
53
54
55
56
57
58
# File 'lib/graphql/schema/validator/format_validator.rb', line 50

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