imbrn / v8n

☑️ JavaScript fluent validation library

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

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Support branching

iangilman opened this issue · comments

I want to be able to validate that something is either undefined or a number, for instance. Is there already a way to do that? If not, it might be worth adding.

Well, considering the API works with a Proxy approach, something you could do might be splitting the rules at the end.

const myVar = 2;

let validation = v8n()
  .myRule()

if (validation.number().test(myVar)) {
  doThis();
} else if (validation.undefined().test(myVar)) {
  doThat();
}

I realize this isn't ideal, since you need two tests. A way of splitting seems like a useful addition, but I'm not part of deciding that.

This branching idea sounds a good feature for me. We can use this thread to discuss how we can achieve this kind of behavior in a clean way.

I think the best syntax would be the modifier syntax already implemented.

v8n()
  .undefined().or.number()
  .test(2)

I'm not sure about. This syntax looks nice, but the way it's supposed to work is a little different from how modifiers are used today.

I don't think it's something impossible to be achieved, but we have to discuss it better to avoid nuances in the API's fluency.

For now, I was thinking of something like a composition of rules, like:

v8n()
  .or(
    v8n().number(),
    v8n().undefined()
  )
  .test(10) // true

Actually, this is going to be just a rule, and it's not an obstacle for us to try to implement oneRule().or.anotherRule() syntax later.

But we have to discuss it anyway.

Yeah, that seems like the straightforward way given the current API, every feature can be improved upon. I do think the or modifier would be possible too, but I haven't tried working on it yet.

The composition idea sounds good to me… That way we can easily support more complicated branching. For instance:

v8n()
  .or(
    v8n().number().positive(),
    v8n().undefined()
  )
  .test(10) // true

I'm not sure how you would do something like that unambiguously with the modifier approach.

BTW, I'm thinking something like either might be a clearer name for this feature. I also figure it might as well take as many arguments as you throw at it. For instance:

v8n()
  .either(
    v8n().number().positive(),
    v8n().undefined(),
    v8n().string().equals('foo')
  )
  .test(10) // true

Of course with multiple arguments, maybe oneOf or any would be even clearer. Any is nice and short as well. So, I guess this is my proposal:

v8n()
  .any(
    v8n().number().positive(),
    v8n().undefined(),
    v8n().string().equals('foo')
  )
  .test(10) // true