Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I validate number of digits in a number using JSON Schema (ajv)?

Tags:

jsonschema

ajv

In a two-factor authentication (2FA) the form ask a code formed by only 6 digits for exampe: 064964

I use the famous Ajv JSON Schema Validator

I can not build the validation scheme for this code:

export const code = {
  'type': 'object',
  'properties': {
     code: {
      'type': ['number'],
       'minimum': 6,
      'minLength': 6
    },
  },
  'required': ['code'],
};

Can you help me?

like image 570
Janka Avatar asked Sep 06 '25 02:09

Janka


1 Answers

minLength only applies to strings, and is not applicable to numbers. Given codes can start with 0, you can't do minimum: 100000.

If you want to use pure JSON Schema to do this, you will need to express your code as a string and not a number.

JSON Schema has no validation key word for "number of digits in a number".

That being said, ajv does allow you to add your own keywords, and write the validation code for them, but that would mean your schemas can't be used by other people.

like image 74
Relequestual Avatar answered Sep 07 '25 22:09

Relequestual