| | |

JSON 16 ๐Ÿ“„ Creating Custom Keywords and Formats

โฑ๏ธ Estimated read: 13 min | |

The JSON Schema specification is designed to be extensible, but the extension mechanism is not the same for the keywords and the formats. A custom keyword is a new assertion that the schema author defines, and the validator must implement the logic. A custom format is a named pattern that the format keyword references, and the validator must register the pattern. The two are the separate surfaces, and the Ajv library implements both with the addKeyword and the addFormat methods . The custom keywords make the schemas more expressive and closer to the application domain, and the custom formats make the string validation reusable across the schemas.

The custom keyword is not portable. A schema that uses a user-defined keyword works only with the validator that implements the keyword, and it requires the additional documentation to maintain . The JSON Schema specification addresses the portability concern with the x- prefix for the custom annotations: a keyword that starts with x- is treated as an annotation, and the validators must not treat it as an assertion . The distinction is the mechanism that separates the application-specific metadata from the standard validation.

Key point: The ajv.addKeyword defines a custom keyword with the keyword name, the optional type and schemaType, and the implementation (the code, the validate, the compile, or the macro function). The ajv.addFormat defines a custom format with a regular expression or a validation function. The custom keywords are non-portable, and the x- prefix is the convention for the custom annotations.


Why the custom keywords and formats exist

The expressiveness problem. The standard keywords cover the common cases, but the application-specific rulesโ€”the date range, the currency amount, the internal identifierโ€”cannot be expressed with the standard vocabulary. The custom keyword is the mechanism that brings the application logic into the schema, and the schema becomes the single source of truth for the validation . The alternative is the validate function in the register options, and the custom keyword is the reusable form of the same logic.

The format reuse problem. The format keyword references a named pattern, and the standard formats are the date, the email, the uri, and the others. The application-specific formatโ€”the employee ID, the product code, the custom slugโ€”needs the custom registration. The addFormat is the mechanism that registers the pattern, and the registered format is the reusable across the schemas . The alternative is the pattern keyword on every field, and the custom format is the named abstraction.

The code-generation problem. Ajv compiles the schema into the JavaScript function, and the custom keyword must participate in the compilation. The code function is the recommended implementation, and it generates the validation code directly . The validate function is the simpler alternative, and it runs the JavaScript validation at the runtime. The compile function is the middle ground, and it returns the validation function from the schema value. The choice is the performance against the simplicity.

The modifying problem. A custom keyword can modify the data during the validation, and the modification is the mechanism for the coercion and the default assignment. The keyword definition must set the modifying: true option, and the modification is the side effect . The data modification is the trade-off against the purity, and the impure validation is the mechanism that the order of the keywords affects.

The annotation problem. A custom keyword that only carries the metadata does not need the validation logic. The x- prefix is the convention for the annotation, and the validators must ignore the unknown x- keywords . The annotation is the mechanism that keeps the schema self-documenting without the validation impact.


a. The custom keywords with the addKeyword

The addKeyword method defines the keyword on the Ajv instance, and the keyword is available only on that instance . The definition has the keyword name, the optional type and schemaType, and the implementation.

// The custom keyword with the compile function
import Ajv from "ajv";

const ajv = new Ajv();

// The range keyword validates the number between the min and the max.
ajv.addKeyword({
  keyword: "range",
  type: "number",
  schemaType: "array",
  compile: ([min, max], parentSchema) =>
    parentSchema.exclusiveRange === true
      ? (data) => data > min && data < max
      : (data) => data >= min && data <= max,
});

const schema = { range: [2, 4], exclusiveRange: true };
const validate = ajv.compile(schema);

console.log(validate(2.01)); // true
console.log(validate(3.99)); // true
console.log(validate(2));    // false
console.log(validate(4));    // false

The compile function receives the keyword’s schema value and the parent schema, and it returns the validation function . The range keyword’s value is the array [2, 4], and the exclusiveRange is the sibling keyword that the compile reads from the parentSchema. The validate function is the result of the compilation, and the data is the value being validated.

The validate function is the simpler implementation. The function receives the schema value, the data, the parent schema, and the data context, and it returns the boolean or the Promise .

// The custom keyword with the validate function
ajv.addKeyword({
  keyword: "isEven",
  type: "number",
  schemaType: "boolean",
  validate: (schema, data) => {
    // The schema is the keyword's value (true or false).
    // The data is the number being validated.
    return schema ? data % 2 === 0 : data % 2 !== 0;
  },
});

const validate = ajv.compile({ isEven: true });
console.log(validate(2)); // true
console.log(validate(3)); // false

The validate function is the mechanism that runs the JavaScript validation at the runtime. The function is simpler than the code function, and the performance is lower because the function is called for every validation . The choice is the simplicity against the speed.

The macro function is the third implementation. The function returns the schema that the keyword expands to, and the expansion is the mechanism that reuses the existing keywords.

// The custom keyword with the macro function
ajv.addKeyword({
  keyword: "range",
  schemaType: "array",
  macro: ([min, max]) => ({
    minimum: min,
    maximum: max,
  }),
});

// The range keyword expands to the minimum and the maximum.

The macro function is the mechanism that translates the custom keyword into the standard keywords, and the translation is the reason the custom keyword can reuse the existing validation . The macro is the simplest implementation, and it is the choice when the custom keyword is the shorthand for the standard combination.


b. The custom formats with the addFormat

The addFormat method defines the named format on the Ajv instance. The format can be a regular expression or an object with the type and the validate function .

// The custom format with the regular expression
ajv.addFormat("identifier", /^a-z\$_[a-zA-Z$_0-9]*$/);

// The custom format with the validation function
ajv.addFormat("byte", {
  type: "number",
  validate: (x) => x >= 0 && x <= 255 && x % 1 === 0,
});

The identifier format is the regular expression, and the string is valid when it matches the pattern . The byte format is the object with the type: "number", and the number is valid when it is the integer between 0 and 255. The type is the mechanism that restricts the format to the specific data type, and the restriction is the reason the format does not apply to the strings.

The custom format is the annotation-only in the newer drafts, and the ajv-formats plugin is the mechanism that provides the standard formats . The plugin is the separate package, and the addFormats(ajv) call registers the formats.

// The ajv-formats plugin
import Ajv from "ajv";
import addFormats from "ajv-formats";

const ajv = new Ajv();
addFormats(ajv);

// The standard formats are now available.

The ajv-formats plugin is the mechanism that provides the date, the time, the email, the uri, and the other standard formats. The plugin is the separate dependency, and the separate dependency is the reason the Ajv core does not include the formats . The custom format is the application-specific addition, and the plugin is the standard baseline.

The security consideration is the separate concern. The format implementations may use the potentially unsafe regular expressions, and the ReDoS attack is the risk . The documentation recommends the assessment of the format’s suitability and the safety for the untrusted data, and the recommendation is the mechanism that keeps the validation safe.


Complete Example Session

// ============================================
// PART 1: THE CUSTOM KEYWORD WITH THE COMPILE
// ============================================

import Ajv from "ajv";

const ajv = new Ajv();

ajv.addKeyword({
  keyword: "range",
  type: "number",
  schemaType: "array",
  compile: ([min, max], parentSchema) =>
    parentSchema.exclusiveRange === true
      ? (data) => data > min && data < max
      : (data) => data >= min && data <= max,
});

// The range keyword is defined.

// ============================================
// PART 2: THE CUSTOM KEYWORD WITH THE VALIDATE
// ============================================

ajv.addKeyword({
  keyword: "isEven",
  type: "number",
  schemaType: "boolean",
  validate: (schema, data) => (schema ? data % 2 === 0 : data % 2 !== 0),
});

// The isEven keyword is defined.

// ============================================
// PART 3: THE CUSTOM KEYWORD WITH THE MACRO
// ============================================

ajv.addKeyword({
  keyword: "range",
  schemaType: "array",
  macro: ([min, max]) => ({ minimum: min, maximum: max }),
});

// The range keyword expands to the minimum and the maximum.

// ============================================
// PART 4: THE CUSTOM FORMAT WITH THE REGEX
// ============================================

ajv.addFormat("identifier", /^a-z\$_[a-zA-Z$_0-9]*$/);

// The identifier format is defined.

// ============================================
// PART 5: THE CUSTOM FORMAT WITH THE VALIDATE
// ============================================

ajv.addFormat("byte", {
  type: "number",
  validate: (x) => x >= 0 && x <= 255 && x % 1 === 0,
});

// The byte format is defined.

// ============================================
// PART 6: THE AJV-FORMATS PLUGIN
// ============================================

import addFormats from "ajv-formats";
addFormats(ajv);

// The standard formats are registered.

// ============================================
// PART 7: THE X- ANNOTATION
// ============================================

// The x- prefixed keyword is the annotation.
const schema = {
  type: "string",
  "x-internal": true, // The annotation is ignored by the validation
};

// The x- prefix is the convention for the custom annotations.

// ============================================
// PART 8: THE MODIFYING KEYWORD
// ============================================

ajv.addKeyword({
  keyword: "trim",
  type: "string",
  schemaType: "boolean",
  modifying: true,
  validate: (schema, data, parentSchema, dataCxt) => {
    if (schema && dataCxt.parentData) {
      dataCxt.parentData[dataCxt.parentDataProperty] = data.trim();
    }
    return true;
  },
});

// The modifying keyword modifies the data.

// ============================================
// PART 9: THE CUSTOM KEYWORD USAGE
// ============================================

const schema = {
  type: "object",
  properties: {
    age: { type: "number", range: [18, 120] },
  },
};

const validate = ajv.compile(schema);

console.log(validate({ age: 25 })); // true
console.log(validate({ age: 150 })); // false

// ============================================
// PART 10: THE CHECKLIST
// ============================================

// [ ] The keyword is defined with the addKeyword.
// [ ] The type and the schemaType are set.
// [ ] The implementation is the code, the validate, the compile, or the macro.
// [ ] The custom format is defined with the addFormat.
// [ ] The ajv-formats plugin is used for the standard formats.
// [ ] The x- prefix is used for the annotations.

The ten parts covered the custom keyword with the compile, the custom keyword with the validate, the custom keyword with the macro, the custom format with the regex, the custom format with the validate, the ajv-formats plugin, the x- annotation, the modifying keyword, the custom keyword usage, and the checklist. The through-line is that the addKeyword and the addFormat are the extension mechanisms, and the custom keywords are the non-portable.


Quick Reference

The addKeyword definition

PropertyPurpose
keywordThe keyword name
typeThe data type the keyword applies to
schemaTypeThe allowed schema value type
compileThe function that returns the validation function
validateThe validation function
macroThe function that returns the expanded schema
modifyingThe keyword modifies the data
validThe pre-defined validation result

The addFormat definition

FormExample
The regular expressionajv.addFormat("id", /^[A-Z]+$/)
The object with the validateajv.addFormat("byte", { type: "number", validate: fn })

The implementation types

TypePerformanceComplexity
codeThe highestThe highest
compileThe highThe medium
validateThe mediumThe low
macroThe highThe lowest

The standard formats

FormatThe plugin
date, time, date-timeajv-formats
email, hostname, ipv4ajv-formats
uri, uri-referenceajv-formats
uuid, regexajv-formats

Best Practices

โœ… Do This:

// Use the compile for the best performance
ajv.addKeyword({ keyword: "range", compile: ([min, max]) => (data) => data >= min && data <= max }); // โœ…

// Use the addFormat for the reusable patterns
ajv.addFormat("identifier", /^[a-z][a-z0-9_]*$/);                   // โœ…

// Use the x- prefix for the annotations
{ "x-internal": true }                                             // โœ…

โŒ Don’t Do This:

// Use the unknown keyword without the addKeyword
{ "range": [2, 4] } // the keyword is ignored                      // โŒ

// Assume the custom keywords are portable
// The custom keywords work only with the Ajv instance.           // โŒ

Common Pitfalls

PitfallWhy It HappensFix
The custom keyword is ignoredThe keyword is not registeredUse the addKeyword
The format is not appliedThe format is not registeredUse the addFormat
The modifying keyword failsThe modifying option is missingAdd the option
The schema is not portableThe custom keyword is usedDocument the requirement

Real-World Examples

1. The custom keyword with the compile

ajv.addKeyword({ keyword: "range", compile: ([min, max]) => (data) => data >= min && data <= max });

2. The custom keyword with the validate

ajv.addKeyword({ keyword: "isEven", validate: (schema, data) => data % 2 === 0 });

3. The custom keyword with the macro

ajv.addKeyword({ keyword: "range", macro: ([min, max]) => ({ minimum: min, maximum: max }) });

4. The custom format

ajv.addFormat("identifier", /^[a-z][a-z0-9_]*$/);

5. The numeric format

ajv.addFormat("byte", { type: "number", validate: (x) => x >= 0 && x <= 255 });

6. The ajv-formats plugin

addFormats(ajv);

7. The x- annotation

{ "x-internal": true }

8. The modifying keyword

ajv.addKeyword({ keyword: "trim", modifying: true, validate: (s, d, p, c) => { c.parentData[c.parentDataProperty] = d.trim(); return true; } });

9. The keyword usage

{ type: "number", range: [18, 120] }

10. The format usage

{ type: "string", format: "identifier" }

Visual

The Custom Keyword

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  THE CUSTOM KEYWORD                                          โ”‚
โ”‚                                                              โ”‚
โ”‚  ajv.addKeyword({ ... })                                     โ”‚
โ”‚         โ”‚                                                    โ”‚
โ”‚         โ–ผ                                                    โ”‚
โ”‚  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”                                    โ”‚
โ”‚  โ”‚ The compile / the   โ”‚  The implementation                โ”‚
โ”‚  โ”‚ validate / the      โ”‚                                    โ”‚
โ”‚  โ”‚ macro               โ”‚                                    โ”‚
โ”‚  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜                                    โ”‚
โ”‚             โ”‚                                                โ”‚
โ”‚             โ–ผ                                                    โ”‚
โ”‚  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”                                    โ”‚
โ”‚  โ”‚ The compiled        โ”‚  The validation function           โ”‚
โ”‚  โ”‚ validate function   โ”‚                                    โ”‚
โ”‚  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜                                    โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

The Custom Format

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  THE CUSTOM FORMAT                                           โ”‚
โ”‚                                                              โ”‚
โ”‚  ajv.addFormat("id", /^[A-Z]+$/)                             โ”‚
โ”‚         โ”‚                                                    โ”‚
โ”‚         โ–ผ                                                    โ”‚
โ”‚  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”                                    โ”‚
โ”‚  โ”‚ The regex or the    โ”‚  The format definition             โ”‚
โ”‚  โ”‚ validate function   โ”‚                                    โ”‚
โ”‚  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜                                    โ”‚
โ”‚             โ”‚                                                โ”‚
โ”‚             โ–ผ                                                    โ”‚
โ”‚  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”                                    โ”‚
โ”‚  โ”‚ { format: "id" }    โ”‚  The format usage                  โ”‚
โ”‚  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜                                    โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

The Portability

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  THE PORTABILITY                                             โ”‚
โ”‚                                                              โ”‚
โ”‚  The standard keyword:                                       โ”‚
โ”‚  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”                                    โ”‚
โ”‚  โ”‚ The portable        โ”‚  The works everywhere              โ”‚
โ”‚  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜                                    โ”‚
โ”‚                                                              โ”‚
โ”‚  The custom keyword:                                         โ”‚
โ”‚  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”                                    โ”‚
โ”‚  โ”‚ The Ajv only        โ”‚  The non-portable                  โ”‚
โ”‚  โ”‚ The x- annotation   โ”‚  The portable annotation           โ”‚
โ”‚  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜                                    โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Summary

ItemValue
The custom keywordajv.addKeyword({ ... })
The custom formatajv.addFormat("name", pattern)
The keyword implementationsThe code, the validate, the compile, the macro
The format formsThe regex or the { type, validate } object
The standard formatsThe ajv-formats plugin
The annotationsThe x- prefix
The portabilityThe custom keywords are non-portable

Key takeaways:

  • The addKeyword defines a custom keyword on the Ajv instance. The keyword is available only on that instance, and the definition has the keyword name, the type, the schemaType, and the implementation . The custom keywords make the schemas more expressive, and the non-portability is the trade-off.
  • The addFormat defines a custom format. The format can be a regular expression or an object with the type and the validate function. The custom format is the reusable pattern, and the ajv-formats plugin is the standard baseline .
  • The implementation choice is the trade-off. The code function is the fastest and the most complex, the validate function is the simplest and the slowest, and the macro function is the shorthand for the standard keywords . The choice is the performance against the simplicity.
  • The x- prefix is the annotation convention. A keyword that starts with x- is treated as an annotation, and the validators must ignore it . The annotation is the mechanism that keeps the schema self-documenting without the validation impact.
  • The modifying keyword has the order dependence. A keyword that modifies the data must set the modifying: true option, and the validation becomes impure. The order of the keywords affects the result, and the separate subschema is the recommendation .

Remember: The JSON Schema extension is the custom keywords and the custom formats. The addKeyword defines the keyword with the code, the validate, the compile, or the macro implementation, and the addFormat defines the format with the regex or the function. The custom keywords are the non-portable, and the x- prefix is the annotation convention. The standard formats are the ajv-formats plugin, and the modifying keywords are the order-dependent.

Was this helpful?


Stop using slow, ad-bloated tool sites! ๐Ÿคฎ

๐Ÿ”Ž Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
โœ… Finance (Mortgage, Interest, Inflation)
โœ… Tech (Base64, JSON, Dev Suite, IP)
โœ… Health (BMI, BMR, TDEE)
โœ… Productivity (Timer, Workspace, QR)

โšก๏ธ Fast & Private
๐Ÿ”’ No data leaves your device
๐Ÿ’Ž 100% Free

๐Ÿ”— Use it now: https://tools.kandz.me
๐Ÿ”– Bookmark itโ€”youโ€™ll need it later!