4

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?

Relequestual
  • 11,631
  • 6
  • 47
  • 83
Janka
  • 1,908
  • 5
  • 20
  • 41

1 Answers1

4

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.

Relequestual
  • 11,631
  • 6
  • 47
  • 83
  • 1
    In fact, you may run into problems, if you're expecting to represent 012345. In fact, javascript may treat a number starting with 0 as octal: https://stackoverflow.com/questions/37003770/why-javascript-treats-a-number-as-octal-if-it-has-a-leading-zero – Relequestual Nov 23 '18 at 16:22
  • 3
    No need for a custom keyword. `pattern` can be used to restrict all the characters in a string to digits. You can enforce the number of digits using the regex or use `minLength`/`maxLength`. – Jason Desrosiers Nov 23 '18 at 17:20
  • In a matter of fact, properly shaped regex in 'pattern' keyword would handle all: just digits, min 6 od them. – PsychoFish Nov 24 '18 at 14:46
  • 1
    Actually, no. `pattern` is only applicable to strings, and is not applicable to other types. Some libraries may automagically cast to a string, but that's not the correct behaviour. There's a test for it, but it doesn't check all other types. Maybe it should. https://github.com/json-schema-org/JSON-Schema-Test-Suite/blob/master/tests/draft7/pattern.json#L17 – Relequestual Nov 26 '18 at 09:09
  • @Relequestual - my comment followed assumption that the digits will be casted to string before validation using JSON schema will be executed. Sorry I didnt underlined it properly earlier. I agree, assumption that it will be converted automagically is careless. One needs to do it explicitly. Once it's done, use `pattern` with fairly simple regex and that's it. Sometimes, depending on regex parser one uses, it'll come for free, but better be safe than sorry. – PsychoFish Nov 26 '18 at 13:52
  • The OP shows their schema uses type `number`, which suggests they are not doing as you describe. If they DID, then sure. – Relequestual Nov 26 '18 at 13:54
  • Wrapping it up: make sure the digit is converted to string and change schema to use string + `pattern` with regex. – PsychoFish Nov 26 '18 at 14:01