Validation

Fields (and their arguments, and input object arguments) can be validated at runtime using built-in or custom validators.

Validations are configured in field(...) or argument(...) calls:

argument :home_phone, String, required: true,
  description: "A US phone number",
  validates: { format: { with: /\d{3}-\d{3}-\d{4}/ } }

or:

field :comments, [Comment], null: true,
  description: "Find comments by author ID or author name" do
  argument :author_id, ID, required: false
  argument :author_name, String, required: false
  # Either `authorId` or `authorName` must be provided by the client, but not both:
  validates required: { one_of: [:author_id, :author_name] }
end

Validations can be provided with a keyword (validates: { ... }) or with a method inside the configuration block (validates ...).

Built-In Validations

All the validators below accept the following options:

For example:

field :comments, [Comment], null: true,
  description: "Find comments by author ID or author name" do
  argument :author_id, ID, required: false
  argument :author_name, String, required: false
  # Include a message for the end user if the validation fails:
  validates required: {
    one_of: [:author_id, :author_name],
    message: "May use either author_id or author_name, but not both."
  }
end

See each validator’s API docs for details:

Some of the validators accept customizable messages for certain validation failures; see the API docs for examples.

Custom Validators

You can write custom validators, too. A validator is a class that extends GraphQL::Schema::Validator. It should implement:

Then, custom validators can be attached either:

Validators are initialized when the schema is constructed (at application boot), and validate(...) is called while executing the query. There’s one Validator instance for each configuration on each field, argument, or input object. (Validator instances aren’t shared.)