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
Manual Validation
You can also manually validate any object against a schema using thevalidate
function:
validate
function will:
- Check that all required fields are present
- Verify types match the schema definition
- Apply any validation rules defined in the schema
- Throw a
ValidationError
if validation fails
ValidationError
When validation fails, aValidationError
is thrown with:
Custom Validation
You can create custom validation rules using thevalidate
option in property definitions:
- 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:- Removing fields not defined in the schema
- Applying any
clean
functions defined on fields - Setting default values for missing fields
clean
function:
Validation in GraphQL Resolvers
When using schemas with GraphQL resolvers, validation happens automatically for parameters:Validation in Schema Definition
When defining a property in a schema, you can specify validation constraints:- A document is validated against the schema (e.g., in MongoDB operations)
- A GraphQL input is processed
- You manually call
clean
orvalidate
on your schema