Skip to content

Commit

Permalink
manually validate a single field
Browse files Browse the repository at this point in the history
This commit resolves issue rickharrison#197 might be helpful as a starting point for issue rickharrison#126

Adds a public valididateOne method to the validateForm object which allows you to validate a single field manually.

/* Usage */  
var valid, field; field = $('[name="name"]).attr('name"); valid = validator.validateOne(field)
if(!valid === true){ 	/* valid === [{name, "name", message="Current error" messages="[Current error, Other errors]"}]
  • Loading branch information
Binary Geometry Limited committed Jan 29, 2018
1 parent 6b7d381 commit 00eb11b
Showing 1 changed file with 70 additions and 0 deletions.
70 changes: 70 additions & 0 deletions validate.js
Original file line number Diff line number Diff line change
Expand Up @@ -412,6 +412,76 @@
}
}
};

/*
* @public
* Accepts a single field name and evaluates against rules for that field
* @param key A string identifying the field as passed to the constructurthe location of the image, relative to the url argument
* @return returns an array of error objects unless validation passes in which case returns true
*/
FormValidator.prototype.validateOne = function(key) {
var field = this.fields[key] || {},
element = this.form[field.name];
/* reset the errors array */
this.errors = [];

if (element && element !== undefined) {
field.id = attributeValue(element, 'id');
field.element = element;
field.type = (element.length > 0) ? element[0].type : element.type;
field.value = attributeValue(element, 'value');
field.checked = attributeValue(element, 'checked');

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

if (field.depends && typeof field.depends === "function") {
if (field.depends.call(this, field)) {
this._validateField(field);

if (this.errors.length > 0){
// console.log('eerrs', this.errors)

return this.errors;
} else {

// console.log('no ers')

return true;
}

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

if (this.errors.length > 0){

return this.errors;
} else {

return true;
}

}
} else {

this._validateField(field);

if (this.errors.length > 0){

return this.errors;
} else {

return true;
}
}
}
return true;
}

/**
* private function _getValidDate: helper function to convert a string date to a Date object
Expand Down

0 comments on commit 00eb11b

Please sign in to comment.