Have you ever use the utility library to validate whether a variable is a valid number? Valid means that the value will not cause an error or will not return an unexpected result, like
NaN. If you have lodash or underscore dependency, you might be tempted to use that
isNumber function. It seems to do just that, right?
Let’s look at both lodash and underscore implementation for
[object Number] string. That applies to not only Number type but also to other types such as Date, function, etc.
You might think it’s fine, but do you aware that
// -> [object Number]
isNumber method isn’t really the correct way for the above use case. We need another validation, that is checking if the number is not
NaN . We will end up with something like this.
const isValidNumber = _.isNumber(obj) && !isNaN(obj)
So how about the
isDate function? What can potentially cause an issue?
Try to initialize invalid Date object, Like
new Date("31/1/2019") or
new Date("test123") . The resulting value will still be a Date object but it will be an invalid Date object. That will likely cause your Date related logic flawed. Therefore we should add another step for validating Date object, maybe this is sufficient:
const isValidDate = _.isDate(obj) && !isNaN(obj.getTime())
- Initializing new date object with invalid string will still return a Date object