Home > front end >  AJV validation in Nodejs
AJV validation in Nodejs

Time:04-23

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;
}

CodePudding user response:

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;
}

CodePudding user response:

Update

There were other mistakes too. The key names must be the same as given in the scheme, otherwise the validation won't work.

Example:

const scheme = {
  type: 'object',
  properties: {
    firstName: {
      type: 'string',
    },
    lastName: {
      type: 'string',
    },
  },
};

// correct - key names are the same
data = {
  firstName: 'Alex',
  lastName: 'Smith',
};

// incorrect - key names aren't the same
data = {
  'first-name': 'Alex',
  'last-name': 'Smith',
};
  • Related