Skip to content
Browse files

Validator: Accept empty optional validation keys

  • Loading branch information...
1 parent 3f4aaf3 commit 22ffda3ed62fcb44ac727a324b4a87d3aa9f95c0 @mendezcode mendezcode committed Sep 26, 2012
Showing with 20 additions and 1 deletion.
  1. +7 −1 lib/validator.js
  2. +13 −0 test/unit/validator.js
View
8 lib/validator.js
@@ -145,7 +145,7 @@ Validator.prototype.validate = function(fields, callback) {
optkeys = this.optional,
messages = this.messages,
rulesCount = this.rulesCount || (this.rulesCount = Object.keys(rules).length);
-
+
// Return missing fields if empty object
if (Object.keys(fields).length === 0 && optkeys.length === 0) {
return this.i18n.missingRequiredFields;
@@ -178,6 +178,12 @@ Validator.prototype.validate = function(fields, callback) {
// Valid is not valid, send error
return messages[key](val);
}
+
+ } else if (optkeys.indexOf(key) >= 0) {
+ // If key is optional, skip & add with null value
+ fields[key] = null;
+ count++;
+ continue;
} else {
// Value is empty, send required fields error
return this.i18n.missingRequiredFields;
View
13 test/unit/validator.js
@@ -155,6 +155,19 @@ vows.describe('lib/validator.js').addBatch({
// Returns errors if required values missing
assert.equal(validator.validate({}), "Missing Required Fields");
+ fields = {
+ name: 'ernie',
+ tag: ''
+ }
+
+ // Accepts empty optional values
+ assert.isNull(validator.validate(fields));
+
+ assert.deepEqual(fields, {
+ name: 'ernie',
+ tag: null
+ });
+
}
},

0 comments on commit 22ffda3

Please sign in to comment.
Something went wrong with that request. Please try again.