A library providing functions that let users validate the values in objects with YAML-formatted rules.
First of all, a list of rules in JSON / YAML format should be provided. Here is the structure of the list:
type Root = {
condition: Condition;
id?: number;
errorMessage?: string;
}[]
type Condition = {
type: string;
field?: string;
arg?: string | null;
args?: (string | null)[];
conditions?: Condition[];
}For example:
[
{
"condition": {
"type": "and",
"field": "name",
"conditions": [
{
"type": "!null"
},
{
"type": "!blank"
}
]
},
"id": 1,
"errorMessage": "\"name\" is required."
},
{
"condition": {
"type": "range",
"field": "age",
"arg": "[18"
},
"id": 2,
"errorMessage": "\"age\" should be >= 18."
}
]using Quicksilver.ObjectValidator;
Validator validator = new(File.OpenText("path/validation-rules.json"));
ValidationResult validationResult = validator.Validate(myObject);import com.quicksilver.objectvalidator.Validator;
// ...
Validator validator = new Validator(getClass().getResource("/path/validation-rules.json"));
ValidationResult validationResult = validator.Validate(myObject);import rules from "path/validation-rules.json";
import { Validator } from "@quicksilver0218/object-validator";
const validator = new Validator(rules);
const validationResult = validator.validate(myObject);Because JSON deserialization in JavaScript / TypeScript does not guarantee runtime safety, objects parsed from JSON must be validated before use to ensure their attributes match the expected types.
e.g. Use zod to check the types first.
import { z } from "zod";
const ObjectSchema = z.object({
id: z.number().optional(),
name: z.string().optional(),
email: z.string().optional(),
});
const result = z
.string()
.transform((str, ctx) => {
try {
return JSON.parse(str);
} catch (e) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: "Invalid JSON",
});
return z.NEVER;
}
})
.pipe(ObjectSchema)
.safeParse(json);
let myObject: z.infer<typeof ObjectSchema>;
if (result.success)
myObject = result.data;
else
console.error(result.error.errors);