Skip to content

Commit

Permalink
Merge pull request #106 from scottluptowski/depends
Browse files Browse the repository at this point in the history
Add ability to conditionally validate certain form fields
  • Loading branch information
rickharrison committed Apr 13, 2014
2 parents b0dc79e + 046e267 commit 4e71814
Showing 1 changed file with 29 additions and 1 deletion.
30 changes: 29 additions & 1 deletion validate.js
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@
this.form = this._formByNameOrNode(formNameOrNode) || {};
this.messages = {};
this.handlers = {};
this.conditionals = {};

for (var i = 0, fieldLength = fields.length; i < fieldLength; i++) {
var field = fields[i];
Expand Down Expand Up @@ -162,6 +163,20 @@
return this;
};

/*
* @public
* Registers a conditional for a custom 'depends' rule
*/

FormValidator.prototype.registerConditional = function(name, conditional) {
if (name && typeof name === 'string' && conditional && typeof conditional === 'function') {
this.conditionals[name] = conditional;
}

// return this for chaining
return this;
};

/*
* @private
* Determines if a form dom node was passed in or just a string representing the form name
Expand All @@ -181,6 +196,7 @@
name: nameValue,
display: field.display || nameValue,
rules: field.rules,
depends: field.depends,
id: null,
type: null,
value: null,
Expand Down Expand Up @@ -209,9 +225,21 @@

/*
* Run through the rules for each field.
* If the field has a depends conditional, only validate the field
* if it passes the custom function
*/

this._validateField(field);
if (field.depends && typeof field.depends === "function") {
if (field.depends.call(this, field)) {
this._validateField(field);
}
} else if (field.depends && typeof field.depends === "string" && this.conditionals[field.depends]) {
if (this.conditionals[field.depends].call(this,field)) {
this._validateField(field);
}
} else {
this._validateField(field);
}
}
}
}
Expand Down

0 comments on commit 4e71814

Please sign in to comment.