How create conditional Validator? #3382
-
In my application there is a form in which some fields depend on others:
If If How do I describe such a scheme? Should I do some validators? Or a few separate forms? So far, I've tried to create several separate validators, but I'm getting a type error const {url, type} = await request.validate(TypeValidator)
const v = getValidatorByType(type)
const {template} = await request.validate(v) // <--
|
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 3 replies
-
Please share the Validator class |
Beta Was this translation helpful? Give feedback.
-
Try this out! |
Beta Was this translation helpful? Give feedback.
-
Alright, so there are a few things here with sub-schemas or passing a union of schemas to the The I have been hesitant to add support for union of schemas because this leads to branching post validation and makes the controllers full of Let's assume that
Now at some stage within your code you will have to write the Instead, what I propose is branching your code into services. Here I have created a sample repo for the same https://github.com/thetutlage/sub-schema-validation. So the idea is.
I think this leads to more maintainable code. |
Beta Was this translation helpful? Give feedback.
-
Alternative solution: TemplateSchemas.ts
(file managing the validation)
|
Beta Was this translation helpful? Give feedback.
Alright, so there are a few things here with sub-schemas or passing a union of schemas to the
request.validate
method.The
request.validate
method cannot work with a union of schemas ( yes, it is a shortcoming ) as it aims to return a single type after validation vs a union of types.I have been hesitant to add support for union of schemas because this leads to branching post validation and makes the controllers full of
if/else
statements.Let's assume that
request.validate(v)
would have worked and it will return thetemplate
property with a union ofNow at some stage within your code you will have to write the
if/else
condition to check if…