AJV validation in Nodejs

Issue

I am getting an error if the allRequired keyword is set. If it’s not given there is no error. The documentation says this keyword must to be given to object types. When it’s not given the validation passes even for wrong input (tested via Postman)

Here is the schema, it’s exported from another file:

const ticketSchema = {
  type: 'object',
  properties: {
    firstName: {
      type: 'string',
      minLength: 1,
    },
    lastName: {
      type: 'string',
      minLength: 1,
    },
    ticketId: {
      type: 'string',
      minLength: 6,
      maxLength: 6,
    },
  },
  allRequired: true,         // <---- error occurs here
};

export default ticketSchema;

Error message:

Error: strict mode: unknown keyword: "allRequired"

Validation

const ajv = new Ajv();
const validateTicket = ajv.compile(ticketSchema);
const ticket = {
    'first-name': firstName,
    'last-name': lastName,
    'route-id': routeID,
  };

const valid = validateTicket(ticket);
if (!valid) {
  res.status(422).send(validateTicket.errors);
  return;
}

Solution

There is no allRequired property in JSON schema. I looked for it up here in specification. It is not there. So, which documentation do you refer to?

There is no allRequired property as far as I know.

But, if you want to make all the properties required, you need to specify a property called required. It is an array with required field names as elements. So, in your case, it would be:

const ticketSchema = {
  type: 'object',
  properties: {
    firstName: {
      type: 'string',
      minLength: 1,
    },
    lastName: {
      type: 'string',
      minLength: 1,
    },
    ticketId: {
      type: 'string',
      minLength: 6,
      maxLength: 6,
    },
  },
  required: ['firstName', 'lastName', 'ticketId']
};

Update:

allRequired is not part of JSON specification. It is part of ajv-keywords module. You need to initialize it as follows:

const Ajv = require('ajv');
const ajv = new Ajv();
require('ajv-keywords')(ajv);

const validateTicket = ajv.compile(ticketSchema);
const ticket = {
    'first-name': firstName,
    'last-name': lastName,
    'route-id': routeID,
  };

const valid = validateTicket(ticket);
if (!valid) {
  res.status(422).send(validateTicket.errors);
  return;
}

Answered By – Tamil Vendhan Kanagarasu

Answer Checked By – Candace Johnson (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.