diff --git a/specs/validate-spec.js b/specs/validate-spec.js index f18f6fc..da5606a 100644 --- a/specs/validate-spec.js +++ b/specs/validate-spec.js @@ -192,6 +192,27 @@ describe("validate", function() { ]); }); + it("does not allow undeclared attributes in exclusive mode", function() { + var attributes = {name: "Nicklas", age: 23, year: 2018} + , globalOptions = {exclusive: true} + , constraints = {name: true}; + expect(validate.runValidations(attributes, constraints, globalOptions)).toHaveItems([ + { + attribute: "age", + value: 23, + globalOptions: globalOptions, + attributes: attributes, + error: "is not permitted (exclusive mode)" + }, { + attribute: "year", + value: 2018, + globalOptions: globalOptions, + attributes: attributes, + error: "is not permitted (exclusive mode)" + } + ]); + }); + it("allows the options for an attribute to be a function", function() { var options = {pass: {option1: "value1"}} , attrs = {name: "Nicklas"} diff --git a/validate.js b/validate.js index 610d0bc..f0141a9 100644 --- a/validate.js +++ b/validate.js @@ -80,6 +80,7 @@ runValidations: function(attributes, constraints, options) { var results = [] , attr + , constraint , validatorName , value , validators @@ -91,6 +92,29 @@ attributes = v.collectFormValues(attributes); } + // In 'exclusive' mode, make sure that there's a constraint for each and + // every attribute. Nested attribute names are matched as well. + if (options.exclusive === true) { + for (attr in attributes) { + value = v.getDeepObjectValue(attributes, attr); + var declared = false; + for (constraint in constraints) { + if (constraint === attr || constraint.indexOf(attr + ".") === 0) { + declared = true; + } + } + if (!declared) { + results.push({ + attribute: attr, + value: value, + globalOptions: options, + attributes: attributes, + error: options.exclusiveErrorMessage || "is not permitted (exclusive mode)", + }); + } + } + } + // Loops through each constraints, finds the correct validator and run it. for (attr in constraints) { value = v.getDeepObjectValue(attributes, attr);