Reputation: 5721
I attempt to validate input in nodejs, such as to make sure it's defined, not null, in case of JSON make sure it has at least one key. Is there's an easier way that using IF condition such as:
if((inputEntity == null) || (!inputEntity))
or
if (Object.keys(inputEntity).length === 0)
I'm aware of the 'validator' package, but I'm not sure it suits my needs. Please advise.
Upvotes: 2
Views: 5690
Reputation: 111336
make sure it's defined, not null
With loose equality:
if (x == null) {
// bad value - null or undefined
}
or with strict equality:
if (x === null || x === undefined) {
// bad value - null or undefined
}
This will not do what you want:
if((inputEntity == null) || (!inputEntity))
because it will match 0, empty string and false
and not only null
and undefined
.
in case of JSON make sure it has at least one key
To check if JSON has at least one key you would need to parse the JSON first with JSON.parse()
and then inspect the resulting object.
To check if an object has at least one key:
if (typeof x === 'object' && Object.keys(x) === 0) {
// object has no keys
}
The typeof
check is needed if you are validating input that you don't know is an object, but you don't want to reject things like numbers that would report having no keys as well. This is just a guess if you want that or not, you didn't provide enough info for us to know for sure.
It would be easier to compare with an empty object but you cannot use ==
or ===
for that. You'd need a library like lodash or some assertion library, testing framework etc. For example with lodash it would be:
if(_.isEqual(x, {})) {
// object has no keys
}
See: https://lodash.com/
Now, if you're serious about input validation then use something like Joi:
It lets you specify your specific validation rules very precisely and easily.
Upvotes: 1