A zero dependency, light weight runtime validator and a schema generator with the final schema as a JSON object which could be easily shared and stored
const PersonSchema = {
name: is.string({ minLength: 2, maxLength: 10 }),
email: is.string({ isEmail: true, minLength: 5 }),
age: is.number({ moreThan: 18 }),
};
This will return a JSON configuration of below shape
{
"name": {
"type": "string",
"rules": {
"minLength": 2,
"maxLength": 10
}
},
"email": {
"type": "string",
"rules": {
"isEmail": true,
"minLength": 5
}
},
"age": {
"type": "number",
"rules": {
"moreThan": 18
}
}
}
Now, we can share this schema with backend (with the help of NPM module) or store it in a DB.
We can also infer the type from the schema with the help of exported type InferType
type Person = InferType<typeof PersonSchema>;
const person: Person = {
name: 'Gaurav Thakur',
email: 'gthakur581@gmail.com',
age: 21,
};
We can also validate schema against the data in runtime
import { is, validateSchema } from 'is-validator';
import type { InferType } from 'is-validator';
const PersonSchema = {
name: is.string({ minLength: 2, maxLength: 10 }),
email: is.string({ isEmail: true, minLength: 5 }),
age: is.number({ moreThan: 18 }),
};
type Person = InferType<typeof PersonSchema>;
const person: Person = {
name: 'A',
email: 'gthakur581@gmail.com',
age: 10,
};
const result = validateSchema(PersonSchema, person);
console.log(result);
output:
Instead of silently returning the error, we could also throw an error by enabling shouldThrowError
property
const result = validateSchema(PersonSchema, person, { shouldThrowError: true });
-
is.string()
- minLength
- maxLength
- isEmail
- isURL
- regex
- endsWith
- startsWith
-
is.number()
- isPositive
- isNegative
- lessThan
- moreThan
-
is.boolean()
- isTruly
- isFalsy
- Add support for more data type e.g. boolean, enums etc
- Add support for more rules
- Add support for making properties optional
- Add support for initializing the schema object when received schema from another source