fastest-validator
fastest-validator copied to clipboard
Is it possible to allow `undefined` value validation but return an error for `null` value?
optional
setting allows undefined
and null
values.
nullable
setting allows null
and disallows undefined
.
What can be done for the case when you want to allow undefined
but disallow null
?
Custom validator :) What is the use-case, and when need this logic?
@icebob This is often helpful because null
and undefined
is not the same :) Especially when you use typescript with strict null checking. Or if you don't want unexpected null
in your documents in db. I think, this case should be built-in, shouldn't it?
@FFKL you can use a clean up function that removes any null key from request body/params.
Please let's keep the validator simple
Also you can test { optional: true, nullable: false }
. maybe it's working, i'm not sure.
@erfanium No, It isn't working;) I I don't think this case is about complicating the validator. Sometimes I want null
in my object for certain keys, sometimes I don't so I can't just use a clean up function. It's about validation logic itself. In my opinion, validator should help me in this base case.
TL;DR: I also think that this behavior should be patched.
This behavior is intended and originate here: https://github.com/icebob/fastest-validator/blob/master/lib/validator.js#L119
IMO, a field could be optional
but specifically not null
.
It's really important with mongo for example because no or undefined
field does not override the field value in document but null
field value does.
As a matter of fact, in JavaScript, null
should always be considered as a value as opposed to undefined
.
undefined
means not set, null
means empty.
Considered a bottle for an analogy: a null bottle could be represented as an empty bottle whereas an undefined bottle would just mean there is no bottle at all.
e.g: consider a JS Object o = {b: null}
, o.a
is considered as undefined
whereas o.b
is considered as null
.
So this code should validate:
it("should not accept null value even if optional", () => {
const Validator = require("fastest-validator");
const v = new Validator();
const schema = {val: {type: "string", nullable: false}};
const check = v.compile(schema);
expect(check({ val: "val" })).toBe(true);
expect(check({ val: undefined })).toBe(true);
expect(check({})).toBe(true);
expect(check({ val: null })).not.toBe(true); // this returns true instead of an error
});
And also this one:
it("should accept null value as required", () => {
const Validator = require("fastest-validator");
const v = new Validator();
const schema = {val: {type: "string", optional: false}};
const check = v.compile(schema);
expect(check({ val: "val" })).toBe(true);
expect(check({ val: undefined })).not.toBe(true);
expect(check({})).not.toBe(true);
expect(check({ val: null })).toBe(true); // this returns an error instead of true
});