Custom validator can be created using
@val.custom decorator, you can wrap the
@val.custom inside a function and make a new validator decorator, and provide logic on the Validator function callback. Validator function signature is like below:
valueis the current value that will be validated. value will always of type string
infois the context information required for validation see below
- return value: return error message if not valid, or return
undefinedfor valid value.
Signature of the
ValidatorContext is like below
namename of the current validating property or parameter
ctxKoa context of current request
parentparent class of current validation property, can be
undefinedif the current validating is a method parameter
For example we will create an age restriction validator which restrict only 18+ age allowed.
Then you can use our new validator like below:
info parameter of the validator function useful when you need to validate value that require request context parameter such as
Sometime its not possible to validate value only on single property, but require multiple properties. Real world example is the confirm password.
Putting validator implementation inside decorator is simple and easy to read, but in some case it might cause circular dependency issue. You can use dependency resolver to solve this issue, by register the validator classes by ID.
The first step, create a class implements
CustomValidator interface like below.
Register the created resolver into the Plumier application
Then use the ID on each authorization applied.
This functionality work well with dependency injection, register the custom validator by name/id and plumier will automatically pass the ID into the custom dependency resolver.