jsoneditor/examples/18_custom_validation.html

111 lines
2.9 KiB
HTML
Raw Normal View History

<!DOCTYPE HTML>
<html>
<head>
<title>JSONEditor | Custom validation</title>
<link href="../dist/jsoneditor.css" rel="stylesheet" type="text/css">
<script src="../dist/jsoneditor.js"></script>
<style type="text/css">
body {
width: 600px;
font: 11pt sans-serif;
}
#jsoneditor {
width: 100%;
height: 500px;
}
</style>
</head>
<body>
<h1>Custom validation</h1>
<p>
This example demonstrates how to run custom validation on a JSON object.
The validation is available in all modes.
</p>
<div id="jsoneditor"></div>
<script>
var json = {
team: [
{
name: 'Joe',
age: 17
},
{
name: 'Sarah',
age: 13
},
{
name: 'Jack'
}
]
};
var options = {
mode: 'tree',
modes: ['code', 'text', 'tree'],
onValidate: function (json) {
// rules:
// - team, names, and ages must be filled in and be of correct type
// - a team must have 4 members
// - at lease one member of the team must be adult
var errors = [];
if (json && Array.isArray(json.team)) {
// check whether each team member has name and age filled in correctly
json.team.forEach(function (member, index) {
if (typeof member !== 'object') {
errors.push({ path: ['team', index], message: 'Member must be an object with properties "name" and "age"' })
}
if ('name' in member) {
if (typeof member.name !== 'string') {
errors.push({ path: ['team', index, 'name'], message: 'Name must be a string' })
}
}
else {
errors.push({ path: ['team', index], message: 'Required property "name"" missing' })
}
if ('age' in member) {
if (typeof member.age !== 'number') {
errors.push({ path: ['team', index, 'age'], message: 'Age must be a number' })
}
}
else {
errors.push({ path: ['team', index], message: 'Required property "age" missing' })
}
});
// check whether the team consists of exactly four members
if (json.team.length !== 4) {
errors.push({ path: ['team'], message: 'A team must have 4 members' })
}
// check whether there is at least one adult member in the team
var adults = json.team.filter(function (member) {
return member ? member.age >= 18 : false;
});
if (adults.length === 0) {
errors.push({ path: ['team'], message: 'A team must have at least one adult person (age >= 18)' })
}
}
else {
errors.push({ path: [], message: 'Required property "team" missing or not an Array' })
}
return errors;
}
};
// create the editor
var container = document.getElementById('jsoneditor');
var editor = new JSONEditor(container, options, json);
editor.expandAll();
</script>
</body>
</html>