So, let's start by adding Ajv to our project's dependencies:
$ yarn add ajv
Then, in src/validators/users/create.js, import the ajv library as well as our two JSON Schemas:
import Ajv from 'ajv';
import profileSchema from '../../schema/users/profile.json';
import createUserSchema from '../../schema/users/create.json';
import ValidationError from '../errors/validation-error';
...
Then, gut out the entire validate function, and replace it with the following:
function validate(req) {
const ajvValidate = new Ajv()
.addFormat('email', /^[\w.+]+@\w+\.\w+$/)
.addSchema([profileSchema, createUserSchema])
.compile(createUserSchema);
const valid = ajvValidate(req.body);
if (!valid) {
// Return ValidationError
}
return true;
}
Next, we will create an instance of Ajv and run the addFormat method to override the default validation function for the email format; the validate function will now use the regular expression we provided to validate any properties with the email format.
Next, we use the addSchema method to supply Ajv with any referenced sub-schemas. This allows Ajv to follow the references and produce a dereferenced, flattened schema, which will be used for the validation operation. Lastly, we run the compile method to return the actual validation function.
When we run the validate function, it will return either true (if it is valid) or false (if it is invalid). If invalid, ajvValidate.errors will be populated with an array of errors, which looks something like this:
[
{
"keyword": "type",
"dataPath": ".bio",
"schemaPath": "#/properties/bio/type",
"params": {
"type": "string"
},
"message": "should be string"
}
]