Is there a way to verify if a property shares the same value as another item within an object array using ajv?

I am currently working on creating a JSON schema to validate cross references using AJV and TypeScript.

Is there a method to verify that a property includes another property from any item within the array (not a specific item in the array)?

Both the property to be checked and the 'source' property are located within items inside object arrays.

For instance:

import Ajv, { ValidateFunction } from "ajv";

const ajv = new Ajv({$data: true, strict: true});

const schema = {
    type: "object",
    properties: {
        things: {
            type: "array",
            items: {
                type: "object",
                properties: {
                    thing_name: {
                        type: "string"
                    }
                }
            }
        },
        other: {
            type: "string",
            enum: { $data: "0/i/dont/know/how/to/address/items/in/this"
        }
    }
}

const validData = {
    things: [
        { thing_name: "foo" },
        { thing_name: "bar" }
    ],
    other: "foo"
}

const invalidData = {
    things: [
        { thing_name: "foo" },
        { thing_name: "bar" }
    ],
    other: "baz"
}

const validator = ajv.compile(schema);

validator(validData) // true
validator(invalidData) // true, but should be false

Even with both validations returning true, I have struggled to create a valid JSON reference that validates correctly.

I attempted using an enum field containing:

{ $data: "0/things/thing_name" }
{ $data: "0/things/0/thing_name" },
{ $data: "0/things/items/properties/thing_name/enum" }

However, due to AJV always validating when it cannot resolve the reference, it is challenging to comprehend the inner workings.

Is there a solution for this, or should I consider implementing a 'helper script'?

Answer №1

To confirm whether the things array includes an item with the value of the other property, you can perform validation. The sequence of the validation process is articulated differently, but the end result will be the same.

const schema = {
    type: 'object',
    properties: {
        things: {
            type: "array",
            contains: { 
                type: "object",
                properties: {
                    thing_name: {
                        const: { $data: '/other'},
                    }
                }
            },
            items: {
                type: "object",
                properties: {
                    thing_name: {
                        type: "string"
                    }
                }
            }
        },
        other: {
            type: 'string',
        },
    },
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The module does not contain 'toPromise' as an exported member in rxjs version 5.5.2

Encountering an error when using toPromise Prior method: import 'rxjs/add/operator/toPromise'; Updated approach: import { toPromise } from 'rxjs/operators'; The new way is causing the following issues: [ts] Module '"d:/.../ ...

Compiling Typescript with union types containing singleton types results in errors

I'm having trouble understanding why the code below won't compile: type X = { id: "primary" inverted?: boolean } | { id: "secondary" inverted?: boolean } | { id: "tertiary" inverted?: false } const a = true const x: X = { id: a ? ...

Issue with PassportJS and Express 4 failing to properly store cookies/session data

I have a situation with my Express 4 app using Passport 0.3.2. I've set up a passport-local strategy, and it's successfully retrieving the user information when the /session endpoint is provided with a username and password. The issue arises whe ...

The term "define" is not recognized when constructing a Next.js application

Currently, I am working with Next version 10.0.1 and React 17.0.2. While attempting to build my Next app, I encountered the following error: ReferenceError: define is not defined at Object.<anonymous> (/Users/username/Desktop/project/node_module ...

Show the distinct values of a mat-select element that retrieves information from an Angular filtered dataSource

Working on an Angular 9 app where data is displayed using a mat-table and filtered based on certain fields. The issue I'm facing is that the dropdown menu shows duplicate values, which is expected since some values may be repeated in the dataset. The ...

Ways to input a return value that may be an array depending on the input

I'm struggling to properly type the return value in TypeScript to clear an error. function simplifiedFn( ids: string | string[], ): typeof ids extends string[] ? number[] : number { const idsIsArray = Array.isArray(ids); const idsProvided = idsI ...

Using Typescript: Utilizing only specific fields of an object while preserving the original object

I have a straightforward function that works with an array of objects. The function specifically targets the status field and disregards all other fields within the objects. export const filterActiveAccounts = ({ accounts, }: { accounts: Array<{ sta ...

Populate input fields in HTML using Angular 4

Within my angular 4 project, I am facing the challenge of setting a value in an input field and in a MatSelect without relying on any binding. Here is the HTML structure: <div class="row search-component"> <div class="col-md-5 no-padding-rig ...

When interacting with the iframe in an Ionic3 app, it suddenly crashes

Greetings! I have integrated a flipping book URL inside an iframe: <ng-container> <iframe [src]="eUrl" id="flipping_book_iframe" frameborder="0" allowfullscreen="allowfullsc ...

Utilizing TypeScript to define React interfaces

How can I effectively utilize two interfaces for the same object? For instance: interface interfaceOne { id: string color: string } interface interfaceTwo { id: string numb: number } I have an Item component that is designed to receive an item ob ...

Initialization error: ServiceIdentifier Symbol(LicencesService) not found in bindings

Encountering an error while compiling the code: Unable to find matching bindings for serviceIdentifier: Symbol(LicencesService) The issue seems to be in the constructor of the HTTP on server.ts file. How can I properly inject the LicencesService? Here is ...

Two services declared with "providedIn: 'root'" that have identical names

Imagine if there are two distinct services in two separate project categories, both sharing the same name. /app/services/category1/my.service.ts: @Injectable({ providedIn: 'root' }) export class MyService { foo() { return 'foo&apo ...

React Material-UI is notorious for its sluggish performance

I recently started using React Material-ui for the first time. Whenever I run yarn start in my react app, it takes quite a while (approximately 25 seconds) on my setup with an i5 8400 + 16 GB RAM. Initially, I suspected that the delay might be caused by e ...

Listening for combinations of keys pressed using HostListener

I've been attempting to detect when a user presses the Shift+Tab key combination on the keyboard, but for some reason I can't get the event to trigger. @HostListener('keyup', ['$event']) @HostListener('keydown', [&a ...

Beware: The use of anonymous arrow functions in Next.js can disrupt Fast Refresh and lead to the loss of local component state

I am currently encountering a warning that is indicating an anonymous object in a configuration file, and even specifying a name for it does not resolve the warning. Below you will find the detailed warning message along with examples. Warning: Anonymous ...

Guide on dynamically applying a CSS rule to an HTML element using programming techniques

Currently working with Angular 6 and Typescript, I am facing a unique challenge. My task involves adding a specific CSS rule to the host of a component that I am currently developing. Unfortunately, applying this rule systematically is not an option. Inste ...

Changing the order of a list in TypeScript according to a property called 'rank'

I am currently working on a function to rearrange a list based on their rank property. Let's consider the following example: (my object also contains other properties) var array=[ {id:1,rank:2}, {id:18,rank:1}, {id:53,rank:3}, {id:3,rank:5}, {id:19,r ...

Using TypeScript generics to add constraints to function parameters within an object

My Goal: Imagine a configuration with types structured like this: type ExmapleConfig = { A: { Component: (props: { type: "a"; a: number; b: number }) => null }; B: { Component: (props: { type: "b"; a: string; c: number }) =& ...

Guide on the correct way to develop a Typescript NPM package accompanied by declarations?

It feels like I'm struggling with a simple task that is driving me crazy. I have several TypeScript files with code that I want to export for an npm package. In order to enable auto-imports from npm packages, all function and constant types need to b ...

A comprehensive guide on utilizing the ngFor directive for looping through objects

After trying to iterate over this dataset within my HTML, I attempted a nested ngfor, but unfortunately encountered an error. My attempt involved iterating the object twice with a nested ngfor, resulting in the following error: HabitRecordsComponent.ht ...