Make numItems work more like isOptional validator #32

Merged
merged 4 commits into from May 7, 2013

Projects

None yet

2 participants

@Kami

This pull request makes numItems validator work more like isOptional validator.

When you add a numItems we now just set the variable on the Chain instance and the actual values are checked and enforced inside a isArray or isHash validator.

@russellhaering russellhaering commented on an outdated diff May 7, 2013
lib/validators.js
@@ -34,3 +34,27 @@ exports.isHostname = function(value) {
return true;
};
+
+/**
+ * Verify that the provided array or object has between min and max number of
+ * elements.
+ * @param {Object} value Object or array to validate.
+ * @param {Number} min Minimum number of elements.
+ * @param {Number} max Maximum number of elements.
+ */
+exports.numItems = function(value, min, max) {
+ var len;
+
+ if (value instanceof Array) {
+ len = value.length;
+ }
+ else {
@russellhaering
russellhaering May 7, 2013

I'd change this to an else if (value instanceof Object) just to make sure you don't have a number or something.

@russellhaering russellhaering commented on the diff May 7, 2013
lib/valve.js
@@ -1350,21 +1351,16 @@ Chain.prototype.numItems = function(min, max) {
max = Infinity;
}
- v.func = function(value, baton, callback) {
- var len;
-
- if (value instanceof Array) {
- len = value.length;
- }
- else {
- len = Object.keys(value).length;
- }
@russellhaering
russellhaering May 7, 2013

Oh, I guess you were just using what was here. I'd still add the extra validation though.

@Kami
Kami May 7, 2013

Yeah, it shouldn't never get called with an invalid value from isHash / isArray, but I agree and it doesn't hurt to add extra validation to isNumber itself - aeb0b31

@russellhaering

I like it, thanks for working on this.

+1

@Kami Kami merged commit dade79c into master May 7, 2013
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment