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:
value
is the current value that will be validated. value will always of type stringinfo
is the context information required for validation see below- return value: return error message if not valid, or return
undefined
for valid value.
Signature of the ValidatorContext
is like below
name
name of the current validating property or parameterctx
Koa context of current requestparent
parent class of current validation property, can beundefined
if the current validating is a method parameter
#
ExampleFor 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 ValidationSometime 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 ImplementationPutting 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.