I am facing an issue with validating an input field (text-area) that receives an array of objects in JSON format. The validation needs to be done at run-time based on an interface created in typescript.
Two interfaces Employee and Address were created with a custom type roleType
interface Employee {
name: string;
age: number;
email: string;
address?: Address;
role?: roleType;
}
interface Address{
city: string;
pinCode: number;
}
type roleType = 'Developer' | 'UI Designer';
Sample valid JSON:
[
{
"name": "John Doe",
"age": 25,
"email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="aac0c5c2c4eacfc7cbc3c684c9c5c7">[email protected]</a>",
},
{
"name": "Jane Doe",
"age": 23,
"email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f99398979cb99c94989095d79a9694">[email protected]</a>",
}
]
Sample invalid JSON:
[
{
"name": "John Doe",
"age": 25,
"language": "typescript",
},
{
"name": "Jane Doe",
"age": 23,
"email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fd979c9398bd98909c9491d39e9290">[email protected]</a>",
}
]
Attempting to validate the array using a function checkArray with the following code:
function checkArray(array: any[]) {
if (!Array.isArray(array)) {
return false;
}
for (let i = 0; i < array.length; i++) {
if (!(array[i] instanceof Employee)) {
return false;
}
}
return true;
}
However, this approach fails because interface Employee is a type and cannot be used as a value with instanceof operator.
I am seeking a way to validate my array with interface type and generate relevant errors without relying on external libraries. Any insights on how to achieve this?