xyz-valid
v1.0.2
Published
Lightweight Typescript schema validation library
Downloads
4
Readme
xyz-valid
A lightweight library for type validation both in the browser and node environments.
npm install xyz-valid
Table of contents:
Assertions
Array
xyz.array(xyz.string()).parse(["foo", "bar", "baz"]);
Boolean
xyz.boolean().parse(true);
Enum
xyz.enum(["foo", "bar", "baz"]).parse("foo");
Literal
xyz.literal("foo").parse("foo");
Number
xyz.number().parse(1);
Min
// Throws an Invalid Min error
xyz.number().min(1).parse(0);
Max
// Throws an Invalid Max error
xyz.number().max(3).parse(4);
Note: .min()
and .max()
can be combined
xyz.number().min(1).max(3).parse(2);
Object
xyz
.object({
foo: xyz.string(),
bar: xyz.number(),
baz: xyz.object({
subfoo: xyz.string(),
subbar: xyz.literal("subbar"),
}),
})
.parse({
foo: "foo",
bar: 1,
baz: {
subfoo: "subfoo",
subbar: "subbar",
},
});
Strict
// Does not throw an error
xyz
.object({
foo: xyz.string(),
bar: xyz.string(),
})
.parse({
foo: "foo",
bar: "bar",
baz: "baz",
});
// Throws an Invalid Strict Object error
xyz
.object({
foo: xyz.string(),
bar: xyz.string(),
})
.strict()
.parse({
foo: "foo",
bar: "bar",
baz: "baz",
});
Compare
xyz
.object({
email: xyz.string(),
verifyemail: xyz.string(),
})
.compare((obj) => obj.email === obj.verifyemail)
.parse({
email: "[email protected]",
verifyemail: "[email protected]",
});
Regex
xyz.regex(/foo/).parse("foobarbaz");
String
xyz.string().parse("foo");
Min
// Throws an Invalid Min error
xyz.string().min(4).parse("foo");
Max
// Throws an Invalid Max error
xyz.string().max(2).parse("foo");
Length
xyz.string().length(3).parse("foo");
Note: .min()
and .max()
can be combined
xyz.string().min(2).max(4).parse("foo");
Modifiers
Optional
xyz.string().optional().parse("foo");
xyz.string().optional().parse(undefined);
Nullable
xyz.string().nullable().parse("foo");
xyz.string().nullable().parse(null);
Transform
xyz
.string()
.transform((str) => parseInt(str))
.parse("1");
Default
// Returns "foo"
xyz.string().optional().default("foo").parse(undefined);
// Returns "bar"
xyz.string().optional().default("foo").parse("bar");