我不明白express-validator中的exists和notEmpty有什么区别,两者的作用是一样的。
exists()
检查请求中是否定义了该属性。notEmpty()
检查属性是否已设置值。在查询参数中(例如),您可以提交
?key=value
,而该值可以是可选的,默认为空字符串。
如果为空或
""
:
notEmpty
返回false
exists
返回true
如果有值:
notEmpty
返回true
exists
返回true
如果钥匙不存在:
notEmpty
返回false
exists
返回false
另一个例子:
/query?param&num=5
exists("param")
返回true
。exists("otherParam")
返回false
。notEmpty("param")
返回false
。notEmpty("otherParam")
返回false
。exists("num")
返回true
notEmpty("num")
返回true
您在对象中具有相同的可能性(甚至更多......):
const obj = {
param: undefined,
notEmpty: null,
null: 0
};
// similar to exists
console.log("param" in obj, "param in obj"); // true
console.log("toString" in obj, "toString in obj"), // true
console.log(obj.hasOwnProperty("param"), "ownProp"); // true
// it is inherited from the Object.prototype
// and has no own toString() function, so we
// expect false
console.log(obj.hasOwnProperty("toString"), "ownProp"); // false
// similar to notEmpty
console.log(obj.param === null, "param === null"); // false
// every property, that doesn't exists,
// returns undefined, but the value
// "undefined" can also be assigned to a
// property
console.log(obj.param === undefined, "param === undef"); // true
console.log(obj.otherParam !== undefined, "otherParam !== undefined"); // false
console.log(obj.otherParam === null, "otherParam === null"); // false
console.log(obj.notEmpty === undefined, "notEmpty === undefined"); // false
// other cases:
// on loosly equal (==), null gets handled equal to undefined
console.log(obj.param == null, "otherParam == null"); // true
console.log(obj.null == null, "0 == null");
// inside a condition, number 0, empty string,
// null and undefined are threaded like "false"
console.log(obj.null ? true : false, "no comparision"); // false