imbrn / v8n

☑️ JavaScript fluent validation library

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

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Add rule "optional"

imbrn opened this issue · comments

This is a simple rule but that can add a lot of flexibility to the library.

It should be a composite rule. It must get a validation as input and should pass when this validation passes or when the validated value is not defined (null or undefined).

const validation = v8n()
  .optional(
    v8n().number().positive()
  );

validation.test(-1); // false
validation.test(1); // true
validation.test(null); // true

Note: its implementation should use check instead of test to provide better error handling.

Lots of validation nesting recently. Could there a nicer way to implement something like this? Maybe another argument on the test functions?

This rule is very straightforward and looks very clean to me. Also, we can benefit from the already implemented error handling system which works very well with rules.

I don't think we need to change our API now just to support this kind of feature. This would be a challenge to make it work for all kind of validations. It would be also hard to make it work with the already in use error handling system.

Is this no basically the same as:

v8n()
  .passesAnyOf(
    v8n().null(),
    v8n().number().positive()
  )
  .test(...);

So this would just be a shortcut for that, yes?

almost that,

actually, we also need to check for undefined:

v8n()
  .passesAnyOf(
    v8n().null(),
    v8n().undefined(),
    v8n().number().positive()
  )

The optional rule would be a kind of a shorthand for that.

I guess it's a fine shortcut then 👍

Can you make a PR for this? 😁