Skip to content
This repository has been archived by the owner on Dec 12, 2021. It is now read-only.

Exclusive attribute validation mode #272

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions specs/validate-spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,16 @@ describe("validate", function() {
]);
});

it("does not allow undeclared attributes in exclusive mode", function() {
var attrs = {name: "Nicklas", age: 23}
, globalOptions = {exclusive: true}
, constraints = {name: true};
expect(validate.runValidations(attrs, constraints, globalOptions)).toHaveItems([{
attribute: "age",
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"}
Expand Down
20 changes: 20 additions & 0 deletions validate.js
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@
runValidations: function(attributes, constraints, options) {
var results = []
, attr
, constraint
, validatorName
, value
, validators
Expand All @@ -91,6 +92,25 @@
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) {
var declared = false;
for (constraint in constraints) {
if (constraint === attr || constraint.indexOf(attr + ".") === 0) {
declared = true;
}
}
if (!declared) {
results.push({
flogiston marked this conversation as resolved.
Show resolved Hide resolved
attribute: attr,
error: "is not permitted (exclusive mode)",
flogiston marked this conversation as resolved.
Show resolved Hide resolved
});
}
}
}

// Loops through each constraints, finds the correct validator and run it.
for (attr in constraints) {
value = v.getDeepObjectValue(attributes, attr);
Expand Down