Skip to content

Instantly share code, notes, and snippets.

@yingliangzhang
Created December 16, 2016 04:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yingliangzhang/63d3373cf91991898a75810bee140038 to your computer and use it in GitHub Desktop.
Save yingliangzhang/63d3373cf91991898a75810bee140038 to your computer and use it in GitHub Desktop.
Unique validation for custom defined fields in an array property for json-editor
JSONEditor.defaults.custom_validators.push(function(schema, value, path) {
let errors = [];
if (schema.type !== 'object') {
return errors;
}
let property = '';
let uniqueValues = [];
let uniqueFieldsStr = '';
Object.keys(schema.properties).forEach(function (propKey) {
property = propKey;
path = 'root.' + property;
const propObj = schema.properties[propKey];
if (propObj.type !== 'array') {
return;
}
if (!('uniqueFields' in propObj)) {
return;
}
uniqueFieldsStr = propObj.uniqueFields.join(', ');
if (!value[propKey].length) {
return;
}
value[propKey].forEach(function(valueObj) {
let fieldValueStr = '';
Object.keys(valueObj).forEach(function (field) {
if (propObj.uniqueFields.indexOf(field) > -1) {
fieldValueStr += valueObj[field];
}
});
uniqueValues.push(fieldValueStr);
});
});
if ((new Set(uniqueValues)).size !== uniqueValues.length) {
errors.push({
path: path,
property: property,
message: 'Value for ' + property + ' must be unique across ' + uniqueFieldsStr
});
}
return errors;
});
@yingliangzhang
Copy link
Author

yingliangzhang commented Dec 16, 2016

To use it, just add "uniqueFields": ["field1", "field2"], to your array property in your schema.json

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment