Skip to main content
Schema validation is a core feature of Orionjs that ensures data conforms to the structure and rules defined in your schemas. This is particularly important for ensuring data integrity in your application.

Automatic Validation

When using a schema with MongoDB collections or GraphQL resolvers, validation happens automatically:
  • MongoDB: Documents are validated before being inserted or updated
  • GraphQL: Input data is validated before being processed by your resolvers
This automatic validation ensures that your data always adheres to your schema rules.

Manual Validation

You can also manually validate any object against a schema using the validate function:
The validate function will:
  1. Check that all required fields are present
  2. Verify types match the schema definition
  3. Apply any validation rules defined in the schema
  4. Throw a ValidationError if validation fails

ValidationError

When validation fails, a ValidationError is thrown with:
For nested fields, the path will include the full path to the field:

Custom Validation

You can create custom validation rules using the validate option in property definitions:
The validate function:
  • Receives the field value as its first parameter
  • Should return an error message string if validation fails
  • Should return nothing (undefined) if validation passes
  • Can be async (returns a Promise)

Advanced Validation

For more complex validation that depends on multiple fields, you can use the options object:

Cleaning Data

Before validation, Orionjs “cleans” the data by:
  1. Removing fields not defined in the schema
  2. Applying any clean functions defined on fields
  3. Setting default values for missing fields
You can manually clean data using the clean function:

Validation in GraphQL Resolvers

When using schemas with GraphQL resolvers, validation happens automatically for parameters:
This ensures that your API is always receiving valid data before it reaches your business logic.

Validation in Schema Definition

When defining a property in a schema, you can specify validation constraints:
The validation will run automatically when:
  1. A document is validated against the schema (e.g., in MongoDB operations)
  2. A GraphQL input is processed
  3. You manually call clean or validate on your schema