imbrn / v8n

☑️ JavaScript fluent validation library

Home Page:https://imbrn.github.io/v8n

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Possibility to validate in relation to other rules

Buzut opened this issue · comments

commented

Thank you very much for this incredible validation library. It's so lightweight and flexible, I use it everywhere and even created a Node.js API validation module on top of it.

I know v8n doesn't aim to mimic Joi, but it also has the ability to validate schemas. Would it be possible to have conditional validation at some point, like XOR, NAND etc?

Let me illustrate this:

const validation = v8n().schema({
  id: v8n()
    .number()
    .positive(),
  name: v8n()
    .string()
    .minLength(4),
  isMarried: v8n()
    .boolean(),
  birthname: v8n() // this one would be required only if isMarried is true
    .string()
    .minLength(4)
});

Hey @Buzut, thank you for your really good question.

Actually, I believe it's possible to implement this feature in some way, and it's something really interesting to do. But we'll probably have to introduce some kind of abstraction in the middle of the schema rule, maybe a function.

What kind of ideas do you have for us to achieve that?

commented

Thank you for your interest in my question.

So to keep the whole library coherent, I'd see something that works in the same way as passesAnyOf. Something like optionalIf (with variants optionalIfOneOf and optionalIfAllOf). It could work like so (the hardest part being how to refer to the actual object property):

const validation = v8n().schema({
  id: v8n()
    .number()
    .positive(),
  name: v8n()
    .string()
    .minLength(4),
  isMarried: v8n()
    .boolean(),
  birthname: v8n() // this one would be required only if isMarried is true
    .string()
    .minLength(4)
    .optionalIf(v8n().schema('isMarried').exact(true))
});

Or if having a polymorphic schema method leads to confusion, we could think of some specific method name like schemaProperty or even a method on schema itself (this would make sense, maintaining the chaining logic).

I think the above would be good style. It seems a bit difficult to implement, but definitely something to look at in my opinion.The main difficulty comes from schema('isMarried') I believe. This requires some sort of reference back to the validation. We would need to go back up the chain. This gets complicated with nested objects. Other than that this is essentially an optional operator, so it's not generally impossible.

I'm gonna close this in favor of the combined issue #191. Thanks for the ideas @Buzut - I hope we can get to this at some point.