all files / keystone/lib/list/ validateInput.js

17.24% Statements 5/29
0% Branches 0/23
0% Functions 0/6
17.86% Lines 5/28
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53                                                                                                
var evalDependsOn = require('../../fields/utils/evalDependsOn.js');
 
function validateInput (item, data, callback) {
	var fieldCount = this.fieldsArray.length;
	var fieldsUpdated = 0;
	var validationErrors = {};
	function addValidationError (path, type, detail) {
		if (detail instanceof Error) {
			detail = detail.name !== 'Error' ? detail.name + ': ' + detail.message : detail.message;
		}
		validationErrors[path] = {
			type: type,
			error: typeof detail === 'string' ? detail : path + ' is ' + type,
			detail: typeof detail === 'object' ? detail : undefined,
		};
	};
	if (this.fieldsArray.length) {
		this.fieldsArray.forEach(function (field) {
			field.validateInput(data, function (valid, detail) {
				if (!valid) {
					addValidationError(field.path, 'invalid', detail);
					complete();
				} else {
					if (field.required && (!field.dependsOn || evalDependsOn(field.dependsOn, data))) {
						field.validateRequiredInput(item, data, function (valid, detail) {
							if (!valid) {
								addValidationError(field.path, 'required', detail);
							}
							complete();
						});
					} else {
						complete();
					}
				}
			});
		});
	} else {
		complete();
	}
	function complete () {
		if (++fieldsUpdated < fieldCount) return;
		if (Object.keys(validationErrors).length) {
			return callback({
				error: 'validation errors',
				detail: validationErrors,
			});
		}
		return callback();
	}
}
 
module.exports = validateInput;