Add .validDate() (#203)

This commit is contained in:
Martin Eneqvist 2024-02-29 08:23:30 +01:00 committed by GitHub
parent 0e687a23a8
commit e9418fe1b9
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 56 additions and 0 deletions

View file

@ -574,6 +574,36 @@ is.all(is.string, '🦄', [], 'unicorns');
//=> false
```
##### .validDate(value)
Returns `true` if the value is a valid date.
All [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date) objects have an internal timestamp value which is the number of milliseconds since the [Unix epoch](https://developer.mozilla.org/en-US/docs/Glossary/Unix_time). When a new `Date` is constructed with bad inputs, no error is thrown. Instead, a new `Date` object is returned. But the internal timestamp value is set to `NaN`, which is an `'Invalid Date'`. Bad inputs can be an non-parsable date string, a non-numeric value or a number that is outside of the expected range for a date value.
```js
const valid = new Date('2000-01-01');
is.date(valid);
//=> true
valid.getTime();
//=> 946684800000
valid.toUTCString();
//=> 'Sat, 01 Jan 2000 00:00:00 GMT'
is.validDate(valid);
//=> true
const invalid = new Date('Not a parsable date string');
is.date(invalid);
//=> true
invalid.getTime();
//=> NaN
invalid.toUTCString();
//=> 'Invalid Date'
is.validDate(invalid);
//=> false
```
##### .validLength(value)
Returns `true` if the value is a safe integer that is greater than or equal to zero.