Custom Validator
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 stringinfois 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 parameterctxKoa context of current requestparentparent class of current validation property, can beundefinedif the current validating is a method parameter
Example#
For example we will create an age restriction validator which restrict only 18+ age allowed.
Then you can use our new validator like below:
The info parameter of the validator function useful when you need to validate value that require request context parameter such as body, params etc.
Class Validation#
Sometime its not possible to validate value only on single property, but require multiple properties. Real world example is the confirm password.
Separate Decorator and Its Implementation#
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.
info
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.
