Created
December 16, 2016 04:36
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To use it, just add
"uniqueFields": ["field1", "field2"],
to your array property in yourschema.json