jsoneditor/examples/18_custom_validation.html

110 lines
2.9 KiB
HTML
Raw Permalink Normal View History

<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<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>
const json = {
team: [
{
name: 'Joe',
age: 17
},
{
name: 'Sarah',
age: 13
},
{
name: 'Jack'
}
]
}
const options = {
mode: 'tree',
modes: ['code', 'text', 'tree', 'preview'],
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
const 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
const 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
const container = document.getElementById('jsoneditor')
const editor = new JSONEditor(container, options, json)
editor.expandAll()
</script>
</body>
</html>