ealush / vest

Vest ✅ Declarative validations framework

Home Page:https://vestjs.dev/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Why `enforce(new Date()).isNotEmpty()` throws

anthony-tron opened this issue · comments

On 4.3.4, as per the documentation says:

enforce([1]).isNotEmpty();
enforce('1').isNotEmpty();
enforce({ 1: 1 }).isNotEmpty();
// passes

However,

enforce(new Date()).isNotEmpty();
// throws?

Expected Behaviour

It passes.

Actual Behaviour

It throws.

What I've tried

enforce(new Date()).isNotEmpty(); // thows unexpectedly
enforce(new Date()).isTruthy(); // passes as expected

Thank you in advance :)

Hey @anthony-tron, thanks for stopping by 👋

TL;DR
A Date object is empty, while still being a truthy value.

I believe your question is something that's worth discussing. At least in terms of internal implementation, both isNotEmpty and isTruthy behave as implemented.

So why does new Date() appears to be empty?

A Javascript Date is an Object

typeof new Date() // 'object'

When going over an object using isEmpty/isNotEmpty we iterate over the object's keys. If there are no object keys, we conclude the object is empty. A Date object has no keys:

Object.keys(new Date()) // []

On the other hand, isTruthy passes correctly, simply because a Date object is not a JS falsy value.

!!new Date() // true

Now, the simple question is - what is the intended validation? Do you wish to check that a Date is not null/undefined?

isNullish/isNotNullish would work.

enforce(new Date()).isNotNullish()

Do you want to check that a date object is before/after some timestamp?

enforce(+someDateObject).greaterThan(Date.now())
enforce(+someDateObject).lessThan(Date.now())

If you have any other validation in mind, I can probably help you achieve it as well.

Thank you very much for replying! I had no idea Object.keys(date) would return [].

The implementation is correct then! Maybe it's worthing adding a little note in the docs.

Now, the simple question is - what is the intended validation? Do you wish to check that a Date is not null/undefined?

I needed both required date fields, and date comparaisons. I already found the workaround you mentioned:

enforce(+date1).greaterThan(+date2); // or date1.getTime();

I love this library, keep up the good work :D